Junior — Middle
В чем различие между оператором throw и throw ex в C# при выбрасывании исключений?
sobes.tech AI
Answer from AI
In C#, the throw and throw ex operators behave differently in terms of call stack when throwing exceptions:
-
throw;— rethrows the current exception, preserving the original call stack. It is used inside a catch block to propagate the exception further without losing information. -
throw ex;— rethrows the exception but resets the call stack, starting it from the current point, which makes debugging more difficult because it loses the original location where the exception was thrown.
Example:
try
{
// code that may throw an exception
}
catch(Exception ex)
{
// Correct:
throw; // preserves the call stack
// Incorrect:
// throw ex; // resets the call stack
}