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.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.