Catch multiple exceptions at once in C#?


In C#, you can catch multiple exceptions at once using a single catch block that includes multiple exception types separated by the pipe `|` symbol. For example:

 

try

{

    // Some code that may throw exceptions

}

catch (IOException | ArgumentException ex)

{

    // Handle IOException or ArgumentException

}


In this example, the catch block will handle both `IOException` and `ArgumentException` exceptions. You can add as many exception types as you need, separated by the `|` symbol.

It's also possible to have multiple catch blocks, each handling a different exception type. In this case, the catch blocks will be executed in order from top to bottom, and the first catch block that handles the exception will be executed. For example:

 

try

{

    // Some code that may throw exceptions

}

catch (IOException ex)

{

    // Handle IOException

}

catch (ArgumentException ex)

{

    // Handle ArgumentException

}


In this example, if an `IOException` is thrown, the first catch block will handle it, and the second catch block will be skipped. If an `ArgumentException` is thrown, the first catch block will be skipped, and the second catch block will handle it.

When catching multiple exceptions, it's important to be careful not to catch exceptions that you don't intend to handle, as this can lead to unexpected behavior in your application.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...