Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor Multiple exception in single catch in jdk 1.6

Is there any alternative in java to make code possible in jdk1.6. I know same is possible in jdk 1.7, but i am stuck with jdk1.6.

Below code can catch multiple exceptions and i want to handle these exception and add it to database table. Since for all 3 exceptions, my exception handling logic is going to remain same. I don't want repeat same code for multiple catch blocks.

try{
      //do somthing here
    }catch(CustomException1 ex1 | CustomException2 ex2 | CustomException3 ex3){
          // Here goes common Exception handing logic.

   }
like image 270
Dark Knight Avatar asked Nov 06 '13 03:11

Dark Knight


2 Answers

try{
  //do somthing here
}catch(Exception e){
     if(e instanceof CustomException1 || e instanceof CustomException2  || e instanceof    CustomException3 ) {
      // Here goes common Exception handing logic.
      } else { throw e;}

}

There is no other option I think.

like image 73
Subin Sebastian Avatar answered Oct 16 '22 17:10

Subin Sebastian


This syntax was added in Java 1.7 because it was difficult to do it cleanly before.

There are a few things you can do:

  • Use a single catch for a common base class of CustomExceptionX (usually Exception, but sometimes you have to go up to Throwable if one of these is actually an Error). The drawback is that it will also catch RuntimeExceptions, so you will have to do a runtime check like Subin suggests. If you are the one defining the CustomExceptionX, you can define a common superclass for this usage and you won't have to do a runtime check.
  • Put your common logic in a function and call this function in both catches. This way the only duplication will be the call to the function.
like image 27
Cyrille Ka Avatar answered Oct 16 '22 15:10

Cyrille Ka