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

Accepted answer
Score: 30

Yes - throw re-throws the exception that was 9 caught, and preserves the stack trace. throw ex throws 8 the same exception, but resets the stack trace to that method.

Unless 7 you want to reset the stack trace (i.e. to shield 6 public callers from the internal workings 5 of your library), throw is generally the better choice, since 4 you can see where the exception originated.

I 3 would also mention that a "pass-through" catch 2 block:

   // do stuff
catch(Exception ex)

is pointless. It's the exact same 1 behavior as if there were no try/catch at all.

Score: 5

Throw will rethrow original exception;

throw 4 ex will create a new exception, so the stack 3 trace changes. Usually makes little sense, in 2 general you should either just throw, or 1 create a new exception and throw that, eg

// not a great code, demo purposes only
catch(FileNotFoundException ex){
throw new ConfigFileNotFoundException("Oops", ex);

More Related questions