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();
  try{
   throwDemo.displayValue();
  }catch(NullPointerException nExp){
   System.out.println("Exception caught in catch block of main");
   nExp.printStackTrace();;
  }

 }
 
 public void displayValue(){
  try{
   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, in the first place it uses the new operator to create an instance of type throwable, in the try block of displayValue() method. 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.

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. Best practices for exception handling in Java
  5. Java Exception Handling interview questions

You may also like -

No comments:

Post a Comment