EXCEPTION HANDLING IN JAVA

So today we are talking about Exception Handling. Before starting we have to know what is mean by Exception handling. So Handling the exception is nothing but converting system error generated message into user friendly error message. Whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so we need to convert it into user friendly error message.we can convert system error message into user friendly error message by using exception handling feature of java.

Hierarchy of Exception classes

The above diagram is the hierarchy of exception classes, we all know that the all classes in java extends the object class in this diagram also Throwable class is the child of object class.Error class is a subclass of Throwable class indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error or StckOverFlowError, though a “normal” condition, but application should not try to catch it.

There is a another class called Exception which is a child class of Throwable ,the exceptions are manageable means we can handle Exceptions.

Type of Exception:

1.CHECKED EXCEPTION:-

This is also known as compile time exception.During compiling compiler gives this error.Here, the JVM needs the exception to catch and handle.

EXAMPLE:- IOException,FileNotFoundException,ClassNotFoundException etc.

import java.io.File;
import java.io.FileReader;

public class FilenotFound_Demo {

public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}

The above program will give the following exceptions.

Output

C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error

2.UN-CHECKED EXCEPTION:-

This is also known as run time exception.This exception occurs at the time of execution. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.

EXAMPLE:-ArithmeticException , NullPointerException, ArrayIndexOutOfBoundException etc.

public class Unchecked_Demo {

public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}

The above program will give the following exception.

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

HANDLING OF EXCEPTIONS:-

To handle those kind of exceptions we have different ways.so Lets discuss about it.

1.Using try catch block:-we write some code and if there is some possibility that the block of code might throw an exception then we surround that code with try and catch block.

If there is some exception occurs in the try block then try block throw and exception and the catch block catch that exception. We also use finally block after catch block the use of that block is it helps to close the resources after the execution of code snippet in try block and also if we want to execute some thing which is necessary even though program is not run properly the code which we are written in the finally block is executed.

Example

public class ExcepTest {   public static void main(String args[]) {      int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
} finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}

This will produce the following result −

Output

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

In the try block if some problem was arrive then we forcefully throw an exception by the help of throw keyword and also we can made our own exception class by extending the class with exception.

Example : Java throw keyword

class Main {
public static void divideByZero() {
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:3)
at Main.main(Main.java:7)
exit status 1

2. Using Throws keyword:- It’s mainly use for checked exception. It’s help to suppress the exception ,it is not handle the exception. It’s use after the method definition before the curly braces.

Example : Java throws Keyword

import java.io.*;
class Main {
public static void findFile() throws IOException {
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e){
System.out.println(e);
}
}
}

Output

java.io.FileNotFoundException: test.txt (No such file or directory)

3. Try with Resources block:- This concept is introduced in java 1.7. In this technique we are writing all of our resources after try. The advantage is , if there is some error occurs with in the try block the resources are automatically closed. No need of finally block.

Example:

import java.io.*;class Main {
public static void main(String[] args) {
String line;
try(BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
while ((line = br.readLine()) != null) {
System.out.println("Line =>"+line);
}
} catch (IOException e) {
System.out.println("IOException in try block =>" + e.getMessage());
}
}
}

Output if the test.txt file is not found.

IOException in try-with-resources block =>test.txt (No such file or directory)

Output if the test.txt file is found.

Entering try-with-resources block
Line =>test line

FLOW DIAGRAM OF EXCEPTION:

The above flow-diagram regarding try-catch-finally construct in Java.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store