开发者

I Need Try Catch Use, Exception Handling and Refactoring Advice

Should I frequently use try catch blocks and how do I determine when and where I need them the most? Also what should do with the exception when it gets caught as a normal practice on small to medium scale departmental business applications? Also is there a free tool 开发者_如何转开发to help me locate duplicate code or code that would be ideal to refactor up the food chain? I've got ReSharper and it's great but I need something to help me analyze what needs to be refactored.

Thanks.


Try..catch blocks should only be used when you can fix the error, are catching in order to perform cleanup before rethrowing (i.e. database rollback), or in a top level catch to log the exception before crashing.

You should never silently swallow exceptions - from that point on your application may be in an inconsistent state and you can't trust it. Best to crash hard with logging information. Consider using Microsoft's crash reporting service as well for debugging and statistical purposes.


I only catch my exceptions when I can do something meaningful with them. Let general exceptions bubble up to the application level and handle it there. This way you can have all your error handling in one location for logging, etc.


try-catch can be used only if you are going to do something useful with the catch part. If all you are going to do is free up resources, you may use try-finally (yes...without the catch). The default exception handling is to throw it. So, maybe you want to log it and then throw it.

Your code should look like

try{
... //do something
}
catch(Exception e){
//log first
throw 
}
finally{
//free up resources.
}

tool wise... you are better off looking at your code in class mode and refactor it by class. This should be more of a design consideration rather than an afterthought.


Well, there are 3 rules I always use as a best practise when handling exceptions:

  • Catch the exception as close as possible to the code which throws the exception
  • ONLY catch an exception when you really can handle it. This involves only catching really specific types of exceptions. NEVER catch an exception you can't handle in normal code, because this will do you no good.
  • Have a global exception handler to catch all exceptions I couldn't handle, used to log the exception and shut down the application.


You should put try...catch blocks around code where you have identified exceptional behaviour that could happen, and that you know how to handle. As you have identified the behaviour, these should be targeted at specific exceptions. They should never be used to suppress errors.

Putting a try..catch block at a high level is useful if you wish to log exceptions. Log 4 .Net is a good tool for this. In a medium-sized company, you may wish to email someone when an exception has occurred, or store it in a database.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜