Rethrowing an exception in java

Normally, catch block are used to handle the exceptions raised in the try block. The exception can re-throw using throw keyword, if catch block is unable to handle it. This process is called as re-throwing an exception.

public class Main {
 
   public int test(int n1, int n2) {
     try{
           return n1/n2;
      }catch(ArithmeticException e){
         throw e; 
      }
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      try{
          System.out.println(main.test(30, 0));
      }catch(Exception e){
          e.printStackTrace();
      }
   }
 
}

Output

java.lang.ArithmeticException: / by zero
        at Main.test(Main.java:5)
        at Main.main(Main.java:14)

Java interview questions on Exception Handling

Please follow and like us:
Content Protection by DMCA.com