Re throwing Exception in Java
When you are using methods in Java and you get any exception using try.catch. You can Re throw the same exception of with extra information to calling method.
public class RethrowExecption {
public static void main(String []a) {
int x=12;
int y=0;
int z=0;
try {
z =divide(x,y);
}catch(Exception e) {
System.out.println("Error in Main ");
e.printStackTrace();
}
System.out.println("Ans in Main :"+z);
}
public static int divide(int x,int y) {
int z=0;
try {
z=x/y;
}catch(ArithmeticException e) {
System.out.println("Error in Method Divide");
e.initCause(new ArrayIndexOutOfBoundsException());
throw e;
}
return z;
}
}
Output :
Error in Method Divide
Error in Main
java.lang.ArithmeticException: / by zero
Ans in Main :0 at RethrowExecption.divide(RethrowExecption.java:22)
at RethrowExecption.main(RethrowExecption.java:10)
Caused by: java.lang.ArrayIndexOutOfBoundsException
at RethrowExecption.divide(RethrowExecption.java:25)
... 1 more
Here original error occurs in method divide() we have handled using catch block. Now We have initialized original cause like ArrayIndexOutOfBounds and resend the exception to main(). In try catch block of main() it will show the details with Cause and Exception.