Sunday, April 22, 2018

Catching .NET exceptions with a condition

CSharp provides methods to catch exceptions only when a condition is met. This can be used for example to display a messagebox when the application is in development and when the application is in the production mode just write to log the exception.

Here is a very simple piece of code. The point in here is to catch the division by zero exception.

bool IsDevelopmentmode = true;

try
{
    for(int i = -2; i <= 2; i++)
    {
        int x = 4 / i;
    }
}
catch (DivideByZeroException ex) when (IsDevelopmentmode)
{
    MessageBox.Show("Error " + ex.Message, "Error",
        MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (DivideByZeroException)
{
    // Log error
}


The code has two catch (DivideByZeroException) statements. The first one has a condition when (IsDevelopmentmode). As long as the condition is true the first catch statement is used. If the condition is false the latter catch statement is executed. As you can see it's possible to mix both conditional and unconditional catch statements. The condition can be any expression that evaluates to boolean value.

There must be at least one catch statement to capture exception. Otherwise the exception is thrown up in the call stack and in the worst case application's user gets the error message. Here is the same example without latter catch statement and the condition is set to false.

bool IsDevelopmentmode = false;

try
{
    for(int i = -2; i <= 2; i++)
    {
        int x = 4 / i;
    }
}
catch (DivideByZeroException ex) when (IsDevelopmentmode)
{
    MessageBox.Show("Error " + ex.Message, "Error",
        MessageBoxButtons.OK, MessageBoxIcon.Warning);
}


Now the exception is not catched and you get following error:


No comments: