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:

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

expert

You have defined a destructor in a class that you have developed by using the C#, but the destructor
never executed. Why?

expert

Implement the Where method in C#. Explain

expert

List some different ways for equality check in .NET

Bình luận

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

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