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

Is there a difference between throw and throw ex ?

Câu trả lời

Certainly! Here's an explanation of the difference between throw and throw ex in C#:

Difference between throw and throw ex

  1. throw:

    • When you use throw without any argument, it re-throws the current exception.
    • It preserves the original stack trace information of the exception.
    • This is useful when you want to handle an exception at a higher level in the call stack without losing the original exception details.
  2. throw ex:

    • Using throw ex re-throws the exception with a new stack trace.
    • It overwrites the original stack trace information with the current stack trace.
    • This can lead to the loss of valuable information about the original exception and its origin.

Here's an example to illustrate the difference:

csharp Copy
try
{
    // Some code that throws an exception
    throw new Exception("Original exception");
}
catch (Exception ex)
{
    // Handling the exception
    Console.WriteLine("Original exception:");
    Console.WriteLine(ex.Message);
    Console.WriteLine(ex.StackTrace);

    // Re-throwing the exception using `throw`
    Console.WriteLine("\nRe-throwing using `throw`:");
    throw;
}

Output:

Copy
Original exception:
Original exceptio...
middle

middle

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

senior

What is Marshalling and why do we need it?

senior

When to use ArrayList over array[] in C#?

senior

When would you use delegates in C#?

Bình luận

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

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