Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch two exceptions in the same catch block?

I have a method that can throw two different exceptions, CommuncationException and SystemException. In both cases I do the same three-line code block.

try {  ... }  catch (CommunicationException ce) {    ... }  catch {SystemExcetion se) {    ...  } 

Is there any possibility to do it like that?

try {    ... }  catch (CommunicationException ce, SystemException se) {    ... } 

Then I would not have to write this much code. I know I could extract the exception handling to a private method, but since the code is only 3 lines long, the method definition would take more code than the body itself.

like image 235
RoflcoptrException Avatar asked Apr 06 '11 08:04

RoflcoptrException


People also ask

Can we catch multiple exceptions in one catch block?

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

How do you handle multiple exceptions in catch block?

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.

Can you throw 2 exceptions?

You can't throw two exceptions.

Can you have two catch statements in Java?

Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.


2 Answers

If you can upgrade your application to C# 6 you are lucky. The new C# version has implemented Exception filters. So you can write this:

catch (Exception ex) when (ex is CommunicationException || ex is SystemException) {     //handle it } 

Some people think this code is the same as

catch (Exception ex) {                     if (ex is CommunicationException || ex is SystemException) {         //handle it     }     throw; } 

But it´s not. Actually this is the only new feature in C# 6 that is not possible to emulate in prior versions. First, a re-throw means more overhead than skipping the catch. Second, it is not semantically equivalent. The new feature preserves the stack intact when you are debugging your code. Without this feature the crash dump is less useful or even useless.

See a discussion about this on CodePlex. And an example showing the difference.

like image 143
Maniero Avatar answered Oct 08 '22 12:10

Maniero


In fact, you could catch only SystemException and it would handle CommunicationException too, because CommunicationException is derived from SystemException

catch (SystemException se) {    ... //this handles both exceptions } 
like image 20
archil Avatar answered Oct 08 '22 12:10

archil