Why should I write a throw when the exception is still bubbling?

Why should I write the throw keyword in a catch block to throw an exception when the exception still grows?

+4
source share
4 answers

First of all, you will do this if you want to make some special logic or error handling logic. Many times it is easy to use try{} finally{} if you need an exception for bubbles, and finally you need to get rid of any resources used.

It can also be used for branching based on debugging or not (so your users donโ€™t see ugly traces of the stack):

  catch(Exception e) { #if DEBUG throw; #else Log(e); #endif } 
+6
source

That way, you can add some information to the exception or change its type, and then re-throw it.

For example, if you tried to parse the employee number pulled from the LDAP server, or something else:

 try { Convert.ToInt32(employeeNumber); } catch(FormatException fe) { throw new ArgumentException("Employee Number" +employeeNumber +" is not valid. ", fe); } 
+3
source

You're not right.

For instance:

 try { // Something throws an exception } catch { } 

This will drown out any exception, so "no exception will pop up."

Perhaps you mean, if it is required to try / catch, to throw exceptions for the calling method or property. Not this.

For IDisposable implementations, you can use it with the operator , so objects will free up basic resources:

 using(disposableObject) { } 

And for others it does not implement IDisposable, you can use try / finally:

 try { // Code } finally { // Do something in any case: even if an exception has been thrown. } 

In any case, note that rethrowing an exception in a catch catch usually loses the contents of the stack trace , so if you need an error report with exception tracking , you need to accept in the attempt / finally approach - or use it if in a batch there are IDisposable objects - (learn more follownig of this link: http://blogs.msdn.com/b/jmstall/archive/2007/02/07/catch-rethrow.aspx )

+1
source

If you do not use the throw keyword inside the catch block, the exception will be no . If everything you do in the catch block is throw (not throw new ), you do not need a catch , and if there is no finally block, you can give up try completely.

+1
source

All Articles