Throw

In try and catch block we can catch the exception but using throw we can throw an exception implicitly.

General Form

throw ThrowableInstance;

ThrowableInstance- Is the object type of the Throwable or the subclass of Throwable.

There are two ways you can obtain a Throwable object:

  1. Parameter in the catch clause.
  2. using new operator to create an object.
//example for throw.
public class ThrowDemo 
{
 static void demoproc() 
 {
 try 
 {
 throw new NullPointerException("demo");  //using new operator creating a NullPointer Exception object which  takes the String value as an argument.
 } 

   catch(NullPointerException e) 
   {
 System.out.println("Caught inside demoproc.::::"+e);  //using  this inside catch block it was caught

 throw e; //throw the catch parameter rethrow the exception to the  outside catch block.
 }
 }
 public static void main(String args[]) {
 try 
 {
 demoproc();
 } 
   catch(NullPointerException e) 
   {
 System.out.println("Recaught::::: " + e); //this caught the throw of Exception parameter of catch block.
 }

 }
}

Output:

Caught inside demoproc.::::java.lang.NullPointerException: demo

Recaught::::: java.lang.NullPointerException: demo

results matching ""

    No results matching ""