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 }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With