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

Why to use lock statement in C#?

expert

in C#, when should we use abstract classes instead of interfaces with extension methods?

middle

Explain Code Compilation in C#

Bình luận

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

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