javaexceptionarithmeticexception

In java how it is possible to catch an exception in a class and throw it to another class to get/print the type of exception


Suppose

class Example1
{
 public static void main(String args[])
 {
  try{
     int num1=30, num2=0;
     int output=num1/num2;
     System.out.println ("Result: "+output);
  }
  catch(Exception e){
     //and in want to determine the type of exception ie- Arithmetic 
      exception on the another class IS IT POSSIBLE? AND HOW
  }
 }
}

and in want to determine the type of exception ie- Arithmetic exception on the another class IS IT POSSIBLE? AND HOW


Solution

  • You can create a utility exception handler class, and expose static method exceprionHandler(Exception exception) method, where you can do handling code.

    like below

    public class ExceptionHandler {
    
    public static  void exceptionHandler(Exception exception){
      //Handling code
    }
    }
    
    class Example1
    {
     public static void main(String args[])
     {
      try{
         int num1=30, num2=0;
         int output=num1/num2;
         System.out.println ("Result: "+output);
      }
      catch(Exception e){
        ExceptionHandler.exceptionHandler(e);
      }
     }
    }