2022-11-07

The Correct Way to Handle Multiple Exceptions in C#

This is just a quick article on the correct way to handle multiple exceptions with the same code in C#. In older versions of C#, one way to handle multiple exceptions was code like this:


    try
    {
        // Code that can fail
    }
    catch (IOException)
    {
       // Failure code A
    }
    catch (ArgumentException)
    {
       // Failure code A
    }

This violates this violates the DRY (Don't Repeat Yourself), concept with Failure code A being repeated. Yes, you can call a method (or even a lamda function) from the failure code, but that creates code that is elsewhere for something that should be handled here. Another attempt would be something like this:


    try
    {
        // Code that can fail
    }
    catch (Exception ex)
    {
        if (ex is IOException || ex is ArgumentException)
        {
            // Failure code A
        }
        else
        {
            throw;
        }
    }

This is better (and the right way in C# before version 6), but it is clumsy. Incidentally, in this code, it would be important to use just throw, not throw ex as C# does not treat them the same. Using just throw preserves the stack trace so that the call stack shows the origination of the exception, whereas throw ex shows the exception originating in this code.

Here is the right way to handle it with current versions of C#:


    try
    {
        // Code that can fail
    }
    catch (Exception ex) when (ex is IOException or ArgumentException)
    {
        // Failure code A
    }

Incidentally, the convention in C# is to use "ex" as the variable for exceptions, as "e" is used for the second argument in event handlers, and if you have exception handling code in an event handler, you don't want them to conflict.

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.