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

senior

What is difference between late binding and early binding in C#?

senior

What happens when we Box or Unbox Nullable types?

expert

Can you add extension methods to an existing static class?

Bình luận

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

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