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) { ... }
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.
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.
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.
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.
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.
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