Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use try multi catch?

I don't understand when to use multi catch. I saw some posts that compile time type of the multi catch exception is the closest super type of multiple exception types.

Lets say there are exception type A,B and their closest super type C.

option 1

try{//whatever}
catch(A|B ex){//whatever}

option 2

try{//whatever}
catch(C ex){//whatever}

option 3

try{//whatever}
catch(A ex){//whatever}
catch(B ex){//whatever}

In which ideal occasions we should use above options when multiple exceptions are thrown?

like image 230
Sanjaya Liyanage Avatar asked Dec 27 '22 01:12

Sanjaya Liyanage


2 Answers

As per the Oracle documentation , the notable points for the new multi-catch block is :

catch (IOException|SQLException ex) {
   logger.log(ex);
   throw ex;
} 

If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block. Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.

If the exceptions can be handled differently then I believe you should catch them separately . If the Exception handling is same for the multiple exception then you can use the multi-catch block.

try{//whatever}
catch(A ex){//do something specific for A}
catch(B ex){//do something specific for B}

try{//whatever}
catch(C ex){
 //C is superclass of A and B and you are not concerned about the specific type 
 // will catch even other exceptions which are instanceof C
}

try{//whatever}
catch(A|B ex){//do the same thing for both A and B}
like image 63
AllTooSir Avatar answered Jan 09 '23 19:01

AllTooSir


Option 1: Avoid duplicate code, if A and B will be are handled the same way.

} catch (SSLException | UnknownHostException e) {
   showErrorPopupAndReturn();
}

Option 2: Almost the same as Option 1, but it will also handle any other subtype of C, which you might not want.

} catch (IOException e) {
   // Almost as Option 1, but will also handle any other subclass of
   // IOException, e.g. ObjectStreamException
   doStuff();
}

Option 3: You have to do something else when A or B occurs.

} catch (UnknownHostException e) {
    tryAnotherIPaddress();
} catch (SSLException e) {
    reloadCertificate();
}
like image 27
jlordo Avatar answered Jan 09 '23 19:01

jlordo