Why should I write throw keyword in catch block to bubble up excep开发者_StackOverflowtion when the exception will go up anyway?
Primarily you would do this if you wanted to do some special logging or error handling logic. Many times it's ok to simply use try{} finally{}
if you need the exception to bubble, and the finally is to dispose of any resources used.
It can also be used to branch based on debugging or not (so your users don't see ugly stack traces):
catch(Exception e)
{
#if DEBUG
throw;
#else
Log(e);
#endif
}
So you could add some information to the exception, or change its type, then re-throw it.
For example, if you were trying to parse an employee number pulled from an LDAP server or something:
try
{
Convert.ToInt32(employeeNumber);
}
catch(FormatException fe)
{
throw new ArgumentException("Employee Number" +employeeNumber +" is not valid. ", fe);
}
You're not right.
For example:
try
{
// Something throws an exception
}
catch
{
}
That would mute any exception, so "no exception is going to bubble up".
Perhaps you mean if it's mandatory to try/catch in order to bubble up exceptions to the caller of some method or property. It's not.
For IDisposable implementations you can use using statement, so object(s) will release underlying resources:
using(disposableObject)
{
}
And for others don't implementing IDisposable, you can use a try/finally:
try
{
// Code
}
finally
{
// Do something in any case: even if an exception has been thrown.
}
Anyway, pay attention to the fact that re-throwing an exception in catch block generally loses stack trace content, so if you need some error reporting with exception tracing, you need to take in consideraion try/finally approach - or using if there're IDisposable objects in the party - (learn more follownig this link: http://blogs.msdn.com/b/jmstall/archive/2007/02/07/catch-rethrow.aspx)
If you don't use the throw
keyword inside a catch block, the exception will not bubble up. If all you do in the catch block is throw
(not throw new
), then you don't need the catch
block, and if there isn't a finally
block, you can forgo the try
entirely.
精彩评论