Why should I write throw keyword in catch block to bubble up exception 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With