Re-Throw Exception Java Example Program


Syntax

try{
   //Do something
}catch(Exception e){
   //throwing caught exception
    throw e;
}

Re-Throw Exception Example Program

public class ReThrowException {
    static void getStringLength(){
        try{
            String text = null;
            int length = text.length();
        }catch(Exception e){
            System.out.println("Caught exception : "+e.toString());
            throw e;
        }
    }
    
    public static void main(String[] args) {
        try{
            getStringLength();
        }catch(Exception e){
            System.out.println("Caught re-thrown exception : "+e.toString());
        }
    }
}

Sample Output

Caught exception : java.lang.NullPointerException
Caught re-thrown exception : java.lang.NullPointerException