Is there a way to catch multiple exceptions at once and without code duplication?
Is there a way to catch multiple exceptions at once and without code duplication?
Yes, there are a couple of ways to catch multiple exceptions at once in C# without code duplication:
You can catch multiple exception types in a single catch block by separating the exception types with the pipe (|) operator. Here's an example:
try
{
// Code that may throw exceptions
}
catch (ArgumentException | NullReferenceException ex)
{
// Handle ArgumentException and NullReferenceException
Console.WriteLine(ex.Message);
}
In this example, if either an ArgumentException
or a NullReferenceException
is thrown within the try block, the catch block will handle both exceptions without duplicating the exception handling code.
You can also catch multiple exceptions by using multiple catch blocks, taking advantage of exception inheritance. If an exception type is not cau...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào