开发者

Throw an exception in try catch block

try { 
  if (isFileDownloaded)
   // do stuff
  else
   throw new CustomException()
} 
catch (Exception e)
{
  // something went wrong to save the error to log
}
finally
{
  //release resources
}

My question is would the catch catches the ApplicationException thrown in the开发者_JS百科 try block? is it in poor coding style?

Should it be written in another way?


The catch will catch your exception (and any other that occurs). That being said, I try to avoid writing code like this when possible.

Personally, I see little reason to ever have exception handling (catch) for an exception thrown in the same scope. If you can handle your error in your method - put the exception handling (ie: logging) directly in the try block as well.

Using a catch is more useful, IMO, for catching exceptions thrown by methods within your try block. This would be more useful, for example, if your // do stuff section happened to call a method that raised an exception.

Also, I recommend not catching every exception (Exception e), but rather the specific types of exceptions you can handle correctly. The one exception to this would be if you're rethrowing the exception within your catch - ie: using it for logging purposes but still letting it bubble up the call stack.


Yes, it will catch ApplicationException as it derives from Exception.

Handling the base exception should be fine in most cases unless you need to log or do something with a different type of exception...

try {
    if (isFileDownloaded)
       doSomeThings();
    else
       throw new ApplicationException("Something expectedly unexpected happened.");
}
catch(ApplicationException e)
{
   // log application exception here...
}
catch(Exception e)
{
   // log all other exceptions here...
}
finally
{
   // release resources...
}


Also, FYI, ApplicationException has been deprecated since .NET 2.0 as an exception to derive from. It was never intended as an exception to throw on its own, so you probably shouldn't use it at all.


Yes the catch would catch your ApplicationException and yes is is poor coding style. As a good general rule only catch specific exception and those that you are going to do something with, like fixing up application state.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜