Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I write throw when exception is bubbled up anyway?

Why should I write throw keyword in catch block to bubble up exception when the exception will go up anyway?

like image 571
eomeroff Avatar asked Dec 21 '22 10:12

eomeroff


2 Answers

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
   }
like image 86
drharris Avatar answered Dec 24 '22 02:12

drharris


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);
}
like image 45
Petey B Avatar answered Dec 24 '22 02:12

Petey B