Monday, 18 May 2015

throw statement in Java exception handling

It is possible for a Java program to throw an exception explicitly, that is done using the throw statement.

General form of throw

The general form of throw is -

throw throwableObject;
Here, throwableObject should be an object of type Throwable or any subclass of it.

We can get this throwableObject in 2 ways -

  • By using the Exception parameter of catch block.
  • Create a new one using the new operator.

Example program using throw

public class ThrowDemo {

 public static void main(String[] args) {
  ThrowDemo throwDemo = new ThrowDemo();
  }catch(NullPointerException nExp){
   System.out.println("Exception caught in catch block of main");

 public void displayValue(){
   throw new NullPointerException();   
  }catch(NullPointerException nExp){
   System.out.println("Exception caught in catch block of displayValue");
   throw nExp;


Note that in this program at two places throw is used. First time, in the try block of displayValue() method, it uses the new operator to create an instance of type throwable. Second time it uses the parameter of the catch block.

The flow of execution, with in a method where throw is used, stops immediately after the throw statement; statements after the throw statement are not executed.

throw statement helps in preserving loose coupling

One of the best practices for the exception handling is to preserve loose coupling. According to that an implementation specific checked exception should not propagate to another layer.

As Example SQL exception from the DataAccessCode (DAO layer) should not propagate to the service (Business) layer. The general practice in that case is to convert database specific SQLException into an unchecked exception and throw it.

catch(SQLException ex){
    throw new RuntimeException("DB error", ex);

That's all for this topic throw statement in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. throws clause
  2. Difference between throw and throws
  3. try-with-resources in Java 7
  4. Creating custom exception class
  5. Java Exception Handling interview questions

You may also like -

No comments:

Post a Comment