It's a question about best .net 开发者_开发技巧practise. I always caught and stored information about exceptions in all of my web and window forms applications as follows:
- Surrounded each method with try catch(Exception exception)
- For any layer except front layer, threw exception to the layer above
- In the front layer, logged the exception to a log file (usually using log4config.dll) and presented a user friendly message to the user.
Is this the best way to handle exceptions? Or should I do something different in my next projects?
I wouldn't add 1 & 2 unless I had some specific reason; for example to alter (wrap) the message; there is no need since exceptions will raise upwards anyway. And done incorrectly you can accidentally remove the all-important stack-trace (throw;
vs throw ex;
- the first being preferred).
The following code is problematic because it overwrites the original stack trace for e
, which makes problems harder to diagnose:
public void Foo() {
try {
Bar();
} catch(Exception e) {
throw e; // re-throw; overwrites original stacktrace in 'e'
}
}
The following code does not have the above stacktrace overwrite problem, but is still unnecessarily verbose:
public void Foo() {
try {
Bar();
} catch(Exception e) {
throw; // re-throw; preserves original stacktrace in 'e'
}
}
Both would be better written as below. This is because, if the only thing you are doing in your catch block is re-throwing the exception, there is no need to write the catch block at all:
public void Foo() {
Bar();
}
The best answer you can get at Best Practices for Handling Exceptions
Here is how NOT to handle exceptions.
public void method1(){
try{
....
// all the code goes here
// declare any helper methods throw throwable
// eg: private boolean check1() throws Throwable{ ...}
....
}catch(Throwable t){
System.out.println("oops...error...good luck debugging. ");
}
}
精彩评论