Exception Handling in Java

Nested Classes

In a previous blog we learned about what Exceptions are, and the types of Exceptions along with its examples. If you want to learn about it visit Exceptions in Java . In this blog, we will go through the approaches of handling Exceptions. It is important to handle exceptions otherwise the code throws exceptions and the program gets terminated. As we all are aware that when the code throws an exception then the code gets terminated. In order to overcome this it is important to handle exceptions. Following are the approaches of handling the exceptions:

  1. try and catch
  2. throw and throws
  3. finally

try and catch

Suppose if the program throws the exception and that exception is not caught anywhere, then the program gets terminated and prints the message on the console with the type of exception. In order to catch the exception which is thrown we use try/catch block. The syntax for try/catch block is:

Syntax

try{
  code
  ......
  }catch(ExceptionType exceptionObj){
  code
  .....
}

If any code inside the try block throws the exception of the class specified in the catch block then:

  1. The program skips the remaining code in the try block.
  2. It executes the statements inside the catch block.

If the code doesn’t try the exception from the try block then it skips the catch block. If the code throws the exception of the other type other than the exception mentioned in the catch block, then the particular method exits immediately.

e.g.

class HandlingArithmeticEx {
  public void calculate(){
    try{
      int a = 90, b = 0;
      int result = a/b;
      System.out.println("Result : "+ result);
    }catch(ArithmeticException ex){
      System.out.println(ex);
    }
  }
  public static void main(String[] args) {
    HandlingArithmeticEx exObj = new HandlingArithmeticEx();
    exObj.calculate();
  }
}

try block reads and processes the byte until we encounter the end of the file. In the above ArithmeticException is thrown, in this case it will skip the statement from the try block and will handle the exception in the catch block and will print the exception on the console. We can also pass the Exception to the method

e.g.

class HandlingArithmeticEx {
  public void calculate() throws ArithmeticException{
    int a = 90, b = 0;
    int result = a/b;
    System.out.println("Result : "+ result);
  }
  public static void main(String[] args) {
    HandlingArithmeticEx exObj = new HandlingArithmeticEx();
    exObj.calculate();
  }
}

When we pass the exception in the calling method then it is mandatory to have throws keyword after the method’s rounded brackets.


Catching Multiple Exceptions

We can catch multiple exceptions in the try block and handle or catch them differently. For doing so we must use a separate catch block for each type. Following is the syntax:

Syntax

try{
  statements that can throw exceptions
}
catch (ArithmeticException e){
  statements for arithmetic expression
}
catch (UnknownHostException e){
  statements for unknown hosts
}
catch (FileNotFoundException e){
  statements for missing files
}
catch (IOException e){
  statements for all other I/O problems
}

e.g.

try {
  fileSearch = new FileInputStream(fileName);
  file = (byte) fileSearch.read();
} catch (IOException ioObj) {
  ioObj.printStackTrace();
} catch (FileNotFoundException fileObj){
  fileObj.printStackTrace();
}

Suppose we wish to write the multiple exceptions in one catch block so that we don’t have to write the catch block again and again and it will also save some time by eliminating the repeated code. Java 7 provides this functionality wherein we can write multiple exceptions in one catch block. The syntax is as follows:

Syntax

try{
  statements that may throw exceptions
}
catch (IOException ioObj | FileNotFoundException ex){
  statements for missing files and all I/O problems
}

e.g.

try {
  fileSearch = new FileInputStream(fileName);
  file = (byte) fileSearch.read();
} catch (IOException ioObj | FileNotFoundException ex) {
  ex.printStackTrace();
}

throw / throws Keyword

We have learned what is throws in the previous section. We can handle the exception by declaring the throws keyword at the end of the signature of the method. We can throw an exception by using throw keyword for an exception that is caught or a new instantiated one. Now you may have a question about what is the difference between throw and throws: throws is used to postpone the handling of an exception and throw is used to invoke the exception explicitly. Lets see the example:

e.g.

class HandlingArithmeticExusingThrow {
  public void calculate(int no1) {
    if(no1 < 18){
      throw new ArithmeticException("Sorry age should be   greater than 18 years");
    }
    else{
      System.out.println("Old Enough");
    }
  }
  public static void main(String[] args) {
    HandlingArithmeticExusingThrow exObj = new HandlingArithmeticExusingThrow();
    exObj.calculate(15);
  }
}

Output

Exception in thread "main" java.lang.ArithmeticException: Sorry Age should be greater than 18 years at HandlingArithmeticExusingThrow.calculate(HandlingArithmeticExusingThrow.java:4)
at HandlingArithmeticExusingThrow.main(HandlingArithmeticExusingThrow.java:12)

Example using throws keyword

e.g

class HandlingArithmeticExUsingThrows {
  public void calculate(int no1) throws ArithmeticException  {
    if(no1 < 18){
      System.out.println("Sorry age should be   greater than 18 years");
    }
    else{
      System.out.println("Old Enough");
    }
  }
  public static void main(String[] args) {
    HandlingArithmeticExUsingThrows exObj = new HandlingArithmeticExUsingThrows();
    exObj.calculate(15);
  }
}

Output

Sorry age should be greater than 18 years

finally block

As we have seen earlier, when our code throws an exception, then stops executing the remaining code and exits the method. This is the problem if the method is using the local resources which that method only knows about , and that particular resource must be cleaned up. The solution for this is to catch all the exceptions, carry out the cleanup and rethrow the exceptions. This solution is tiring because we need to clean up the resource allocation in two places: in the normal code and in the exception code. In order to solve this problem finally block can be used. In the finally block code also executes whether the exception was caught or not. We will go through the example:

Syntax

try {
  statements
} catch (ExceptionType ex) {

} catch (ExceptionType ex1) {

} catch (ExceptionType ex2) {
  statements
}finally {
  statements
}

e.g.

public class FinallyEx {
  public static void main(String args[]) {
    int array[] = new int[4];
    try {
      System.out.println("Access element 5 :" + array[5]);
    } catch (ArrayIndexOutOfBoundsException ex) {
      System.out.println("Exception thrown  :" + ex);
    }finally {
      array[0] = 90;
      System.out.println("0th index element: " + array[0]);
    }
  }
}

Output

Exception   :java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5
0th index element: 9
Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.