Câu hỏi phỏng vấn C#
Câu hỏi

Is there a way to catch multiple exceptions at once and without code duplication?

Câu trả lời

Yes, there are a couple of ways to catch multiple exceptions at once in C# without code duplication:

Using a Single catch Block with Multiple Exception Types

You can catch multiple exception types in a single catch block by separating the exception types with the pipe (|) operator. Here's an example:

csharp Copy
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.

Using Multiple catch Blocks with Exception Inheritance

You can also catch multiple exceptions by using multiple catch blocks, taking advantage of exception inheritance. If an exception type is not cau...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the use of Null Coalescing Operator ( ?? ) in C#?

middle

What is scope of a Internal member variable of a C# class?

junior

Can this be used within a Static method?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào