Can anyone tell me difference between throw
and throw ex
in brief?
I read that throw
stores previous exceptions, not getting this line.
Can i get this in brief with example?
The throw keyword is used to throw an exception explicitly. It can throw only one exception at a time. The throws keyword can be used to declare multiple exceptions, separated by a comma.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Throw expressions are the way to tell compiler to throw exception under specific conditions like in expression bodied members or inline comparisons. This example uses simple Person class to demonstrate different situations where throw-expressions can be used: auto-property initializer statement.
In the following example, a throw expression is used with a null-coalescing operator to throw an exception if the string assigned to a Name property is null . C# Copy. public string Name { get => name; set => name = value ?? throw new ArgumentNullException(paramName: nameof(value), message: "Name cannot be null"); }
Yes - throw
re-throws the exception that was caught, and preserves the stack trace. throw ex
throws the same exception, but resets the stack trace to that method.
Unless you want to reset the stack trace (i.e. to shield public callers from the internal workings of your library), throw
is generally the better choice, since you can see where the exception originated.
I would also mention that a "pass-through" catch block:
try
{
// do stuff
}
catch(Exception ex)
{
throw;
}
is pointless. It's the exact same behavior as if there were no try/catch
at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With