You are here: Home / Topics / Throw statement example in Java

Throw statement example in Java

Filed under: Java on 2023-09-19 06:48:47

//  Program to use throw statement to raise exception and rethrow the exception.

class  ThrowExceptionExample 
{
static void demoproc() 
{
 try 
 {
  throw new NullPointerException("demo");
 } 
 catch(NullPointerException e) 
 {
  System.out.println("Caught inside demoproc.");
  throw e;   // rethrow the exception
 }
}

public static void main(String args[ ]) 
{
 try 
 {
  demoproc();
 } 
 catch(NullPointerException e) 
 {
  System.out.println("Recaught: " + e);
 }
}
}


Output:

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

About Author:
S
Shyam Dubey     View Profile
I am a good learner. I like posting new questions on this plateform to help other students.