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

Yes, in C# you can catch multiple exceptions at once using a single catch block, reducing code duplication. This feature is available from C# 6.0 onwards and is known as “exception filtering” or “multi-catch”.

To catch multiple exceptions using a single catch block, you can specify the exception types separated by the when keyword followed by a condition that determines when the catch block should be executed. This allows you to handle different exceptions differently based on specific conditions.

Here’s an example that demonstrates catching multiple exceptions using a single catch block:

try
{
    // Code that may throw exceptions
}
catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException)
{
    // Handle ArgumentException or InvalidOperationException
    // Specific exception handling logic
}

In this example, the catch block catches exceptions of type ArgumentException or InvalidOperationException. The when keyword is used to specify the condition for when the catch block should be executed, in this case, if the caught exception is of either of those types.

Using exception filtering, you can specify multiple exception types and provide custom handling for each type while avoiding code duplication. It improves code readability and maintainability by consolidating exception handling logic.

It’s important to note that when using exception filtering, the catch block executes only if the exception type matches the specified types and the condition evaluates to true. If the condition evaluates to false, the catch block is skipped, and the exception is propagated to the next higher-level exception handler or the application terminates if there are no further exception handlers.

However, it’s generally recommended to handle exceptions based on their specific types whenever possible, as catching all exceptions in a single catch block can make the code less precise and can hide potential errors or bugs. Using exception filtering should be done judiciously and when it improves the overall readability and maintainability of the code.

error: Content is protected !!