12

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?

Hoh
  • 1,196
  • 1
  • 12
  • 30
maverickabhi
  • 197
  • 1
  • 6
  • 21
  • 3
    http://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex – Random Feb 13 '14 at 14:07
  • 1
    `throw`, without a parameter is used in a `catch` block to rethrow an exception that caused the `catch`. – Jodrell Feb 13 '14 at 14:17

2 Answers2

30

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • 5
    Its not pointless if you put a log statement before throw. Thats how I use it quite often. – Evgeni Feb 13 '14 at 14:26
  • 18
    @Eugene You are right, but I don't have anything before the throw - that's what I was intending to illustrate. – D Stanley Feb 13 '14 at 14:42
5

Throw will rethrow original exception;

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

// not a great code, demo purposes only
try{
File.Read("blah");
}
catch(FileNotFoundException ex){
throw new ConfigFileNotFoundException("Oops", ex);
}
Evgeni
  • 3,341
  • 7
  • 37
  • 64
  • I have used this pattern, the `throw new Exception...`, on more than one occasion, usually only if I have been painted into a corner by existing code. If I have time/access/permission to change *upstream* code I will try to refactor to not need this. However, I have occasionally used this pattern in greenfield code, too. – Andrew Steitz Aug 19 '15 at 15:49