Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between throw and throw ex in c# .net [duplicate]

Tags:

c#

throw

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?

like image 427
maverickabhi Avatar asked Feb 13 '14 14:02

maverickabhi


People also ask

What is the difference between the throw and throws keyword?

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.

What is a throw clause?

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.

What is throw expression?

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.

What is throw statement in C#?

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"); }


1 Answers

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.

like image 183
D Stanley Avatar answered Sep 30 '22 18:09

D Stanley