01 Jun

Handling Exception with ‘When’ clause in Catch block

Introduction:

C# 6.0 introduced several language enhancements to make code more expressive and developer friendly. One notable addition was the introduction of the ‘When’ clause in catch blocks, providing developers with a powerful tool for more refined exception handling.

Exception Handling Basics:

In C#, exception handling is typically done using try, catch, and optionally, finally blocks. The catch block catches and handles exceptions of a specified type.

try
{
    // Code that might throw an exception
}
catch (ExceptionType ex)
{
    // Handle the exception
}

The ‘When’ Clause:

The ‘When’ clause extends the catch block by allowing developers to specify conditions under which the catch block should be executed. This enhances the granularity of exception handling, enabling more precise control over how different exceptions are managed.

try
{
    // Code that might throw an exception
}
catch (ExceptionType ex) when (SomeCondition)
{
    // Handle the exception only if SomeCondition is true
}

Practical Examples:

Handling Specific Error Codes:

try
{
    // Code that might throw exceptions
}
catch (CustomException ex) when (ex.ErrorCode == 500)
{
    // Handle exceptions with a specific error code
}
catch (Exception ex)
{
    // Handle other exceptions
}

Combining Multiple Conditions:

try
{
    // Code that might throw exceptions
}
catch (CustomException ex) when (ex.ErrorCode == 500 && ex.CanRetry)
{
    // Handle exceptions with a specific error code and retry flag
}
catch (Exception ex)
{
    // Handle other exceptions
}

Conclusion:

The ‘When’ clause in catch blocks introduced in C# 6.0 significantly enhances the flexibility of exception handling. By allowing developers to specify conditions for exception handling, it promotes more robust and targeted error management in C# applications. Utilizing this feature appropriately can lead to cleaner and more maintainable code when dealing with unexpected runtime issues.

About the Author

Comments are closed.