Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More Elegant Exception Handling Than Multiple Catch Blocks? [duplicate]

Using C#, is there a better way to handle multiple types of exceptions rather than a bunch of ugly catch blocks?

What is considered best practice for this type of situation?

For example:

try {     // Many types of exceptions can be thrown } catch (CustomException ce) {     ... } catch (AnotherCustomException ace) {     ... } catch (Exception ex) {     ... } 
like image 580
Aaron Avatar asked Apr 26 '09 19:04

Aaron


People also ask

Is there a way to catch multiple exceptions at once and without code duplication?

In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.

Can we use multiple catch blocks in exception handling?

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.

How do you handle different types of exceptions using multiple catch statements?

The Try Block If your code throws more than one exception, you can choose if you want to: use a separate try block for each statement that could throw an exception or. use one try block for multiple statements that might throw multiple exceptions.

Can one catch blocks efficiently trap and handle multiple exceptions?

In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication.


1 Answers

In my opinion, a bunch of "ugly" catch blocks IS the best way to handle that situation.

The reason I prefer this is that it is very explicit. You are explicitly stating which exceptions you want to handle, and how they should be handled. Other forms of trying to merge handling into more concise forms lose readability in most cases.

My advice would be to stick to this, and handle the exceptions you wish to handle explicitly, each in their own catch block.

like image 109
Reed Copsey Avatar answered Sep 22 '22 19:09

Reed Copsey