Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I execute multiple Catch blocks?

This is a bit abstract, but is there any possible way to throw an exception and have it enter multiple catch blocks? For example, if it matches a specific exception followed by a non-specific exception.

catch(Arithmetic exception) {   //do stuff } catch(Exception exception) {   //do stuff } 
like image 607
jon Avatar asked Oct 27 '10 16:10

jon


People also ask

Can I execute multiple catch blocks without try block?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.

How many catch blocks are allowed?

No. Only one catch block execute at a time. We can have multiple catch blocks but only one catch block will be execute at a time.

How does multiple catch block work?

Multiple Catch Block in Java Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency.


1 Answers

It is perfectly acceptable to have multiple catch blocks of differring types. However, the behavior is that the first candidate block handles the exception.

It will not enter BOTH catch blocks. The first catch block that matches the exception type will handle that specific exception, and no others, even if it's rethrown in the handler. Any subsequent ones will be skipped once an exception enters a catch block.

In order to have an exception caught in BOTH blocks, you would need to either nest blocks like so:

try {      try      {         // Do something that throws  ArithmeticException      }      catch(ArithmeticException arithException)      {         // This handles the thrown exception....          throw;  // Rethrow so the outer handler sees it too      } } catch (Exception e) {    // This gets hit as well, now, since the "inner" block rethrew the exception } 

Alternatively, you could filter in a generic exception handler based on the specific type of exception.

like image 196
Reed Copsey Avatar answered Oct 03 '22 04:10

Reed Copsey