Exception Handling in Java

This article provides an introduction to exception and exception handling in Java.

 

Exceptions in Java

 

Exceptions represent exception conditions that alter the normal program flow. Exceptions can be hardware failure, resource availability,or even code issues or bugs.

 

Every exceptions an instance of a class that has Exception class in its inheritance hierarchy. So, exceptions are always some subclass of java.lang.Exception.

 

Exception class again derives from class Throwable.

 

 

Exception Hierarchy

 

There are two subclasses of Throwable :

1) Exception

2) Error

 

exception hierarchy

 

Errors

 

Errors represent unusual situations that are not caused by program errors. Generally, the application won’t be able to recover from an Error, so programmer is not required to handle them by catching or rethrowing.

 

For example,

OutofMemory error

 

Exceptions

 

Normally, Exceptions occur because some resource is not available rather than programmatic issue.

 

For example,

IOException

FileNotFoundException

 

RunTime Exceptions

 

RunTimeException is a subtype of Exception. These are special because they sometimes indicate program errors.

 

For Example,

NullPointer Exception

 

Difference between checked vs unchecked Exceptions

 

Checked exceptions include all subtypes of Exception, excluding classes that extend RunTimeException.

 

Checked exception are subject to handle the exception using try/catch or declare them using throws.

 

Subtypes of Error or Runtime exceptions are referred to as unchecked exceptions.

 

Compiler does not check if you declared or handled them. Even if a method does declare a RunTimeException, the calling method is not required to handle it.

 

Difference between JVM Thrown Exceptions vs Programmatic Exceptions

 

Programmatic exceptions are thrown by the programmers or application. The programmatic exceptions expects issues while parsing some input or when a method receives an argument formatted differently that what the method expects.

 

Some examples of Programmatic Exceptions are :

NumberFormatException, IllegalArgumentException

 

JVM Thrown Exceptions are exceptions/errors thrown by JVM. These exceptions are not recognized by the compiler.. JVM throws the exceptions while executing corresponding code.

 

Examples of JVM thrown exceptions are :

Null Pointer Exception, ArrayIndexOutOfBoundsException

 

Exception handling using try and catch

 

To handle an exception or error, simply enclose the code that you want to monitor inside a try block. Immediately after the try block, include a catch block that specifies the exception type that you wish to catch.

 

Here is an example of this:

 

public class ExceptionExample {

  public static void main(String[] args) {
    int num = 10;
    int div = 0;
    
    try{
      
      int q = num/div;
    }
    catch(ArithmeticException e){
      System.out.println("Exception : " + e);
    }
  }

}


 

Multiple catch clauses

 

If more that one exception can be raised by a single piece of code, you can specify two or more catch clauses, each specifying a different type of exception.

 

When an exception is thrown, each catch statement is inspected in order and the first one whose type matches with the exception that occurred, gets executed.

 

Here is a piece of code that can raise a divide by zero and array index exception.

 

package quiz;

public class ExceptionExample {

  public static void main(String[] args) {
    int num = 10;
    int div = 0;
    int arr[] = {1};
    try{
      
      int q = num/div;
      arr[10] = 11;
    }
    catch(ArithmeticException e){
      System.out.println("Exception : " + e);
    }
    catch(ArrayIndexOutOfBoundsException e){
      System.out.println("Exception : " + e);
    }
  }

}


 

throw statement

 

A throw statement lets us throw an exception explicitly.

 

Here is the syntax of it :

 

throw throwableInstance;

 

Here, throwableInstance is of type Throwable or it subclass.

 

We can obtain a Throwable object in the catch clause or creating one using new operator.

 

The flow of execution stop immediately after a throw statement is encountered and the nearest enclosing try block is inspected to see if its catch statement matching the type of exception. If a match is found, control is transferred to that statement, else the next enclosing try is inspected.

 

If no matching catch is found, then the default exception handler halts the program and prints the stack trace.

 

Here is an example that creates and throws an exception. The handler that catches it, again rethrows it to outer handler.

 

public class ThrowDemo {
  
  public static void main(String[] args){
    try{
      throwMethod();
    }
    catch(NullPointerException e){
      System.out.println("Caught again in main");
    }
  }
  
  static void throwMethod(){
    try{
      throw new NullPointerException();
    }
    catch(NullPointerException e){
      System.out.println("Caught in throwMethod.. rethrowing");
      throw e;
    }
  }

}


Here is the output of the above program :

Caught in throwMethod.. rethrowing

Caught again in main

 

throws clause

 

If a method causing an exception does not handle it, then it must specify that it can throw the exception using throws clause.

 

Here is an example of method that specifies the exception it may throw using throws clause.

 

package topjava;

public class ThrowDemo {
  
  public static void main(String[] args){
    try{
      throwMethod();
    }
    catch(IllegalAccessException e){
      System.out.println("Caught again in main");
    }
  }
  
  static void throwMethod() throws IllegalAccessException{

      throw new IllegalAccessException();
    
  }

}


 

The throwMethod() does not handle the IllegalAccessException and notifies the caller of it using throws clause. The method calling it(main method) handles it.

finally

 

finally creates a block of code that will be executed after a try/catch block has completed. The finally clause if optional.. however, each try block needs at least one catch or finally clause.

 

The finally will execute whether or not an exception is thrown.

 

If an exception is thrown, the finally block even if no catch statements match the exception or catch statements are not present.

 

Any time a method is about to return form a try/catch block, the finally executes just before the method returns.

 

Here is an example of finally clause :

 

package topjava;

public class FinallyDemo {

  public static void main(String[] args) {
    try{
      method();
    }
    catch(Exception e){
      System.out.println("Exception caught");
    }
    finally{
      System.out.println("finally in main executed");
    }
  }
  
  static void method(){
    try{
      throw new RuntimeException();
    }
    finally{
      System.out.println("finally of method executed");
    }
  }

}


 

Here is the result of the above program:

finally of method executed

Exception caught

finally in main executed

 

 

 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

2 comments

  1. very good topic expection handling…………….great

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: