What makes a "roll"? do it by yourself?

Possible duplicate:
difference between throw and throw new Exception ()

What is the point of having

catch (Exception) { throw; } 

What does it do?

+47
c # exception
Apr 28 '10 at 10:33
source share
5 answers

The throw keyword itself simply re-throws the exception found above in the catch statement. This is convenient if you want to perform some rudimentary exception handling (possibly a compensating action, for example, rollback a transaction), and then rebuild the exception on the calling method.

This method has one significant advantage over catching an exception in a variable and throwing this instance: it saves the original call stack. If you catch (Exception ex) and then throw ex, your call stack will only start with this throw statement and you will lose the method / line of the original error.

+77
Apr 28 '10 at
source share

Sometimes you can do something like this:

 try { // do some stuff that could cause SomeCustomException to happen, as // well as other exceptions } catch (SomeCustomException) { // this is here so we don't double wrap the exception, since // we know the exception is already SomeCustomException throw; } catch (Exception e) { // we got some other exception, but we want all exceptions // thrown from this method to be SomeCustomException, so we wrap // it throw new SomeCustomException("An error occurred saving the widget", e); } 
+11
Apr 28 '10 at
source share

He repeats the same mistake, you get nothing from it.
Sometimes you can use the catch method to do some sort of logging or something else without going through your exceptions like this:

 catch (Exception) { myLogger.Log(LogLevels.Exception, "oh noes!") throw; } 

I initially mistakenly thought that this would spin your stack, but this will only happen if you do the following:

 catch (Exception err) { throw err; } 
+3
Apr 28 '10 at
source share

The only reason I can think of is if you want to set a breakpoint there during debugging.
This is also the default code generated by some tools that I think.

+3
Apr 28 '10 at 10:35
source share

Just flip the current exception and this exception will save its โ€œsourceโ€ and stack trace.

+2
Apr 28 '10 at 10:39
source share



All Articles