Junior — Middle
How can you implement error handling for different types of errors using try-catch?
sobes.tech AI
Answer from AI
In C#, to handle different types of errors in a try-catch construct, you can use multiple catch blocks, each of which intercepts exceptions of a specific type. This allows for different handling of various exceptions.
Example:
try
{
// Code that may throw an exception
}
catch (ArgumentNullException ex)
{
// Handling null argument exception
}
catch (InvalidOperationException ex)
{
// Handling invalid operation exception
}
catch (Exception ex)
{
// General handling of all other exceptions
}
You can also use exception filters (catch with a condition) to more precisely control handling:
catch (Exception ex) when (ex.Message.Contains("specific error"))
{
// Handling exception with a specific condition
}
It is important to place more specific catch blocks above general ones so they are not caught earlier. This approach allows flexible and safe handling of different errors.