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

expert

Could you explain the difference between destructor , dispose and finalize method?

entry

What is an Object ?

middle

What is difference between constant and readonly ?

Bình luận

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

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