Reputation: 15598
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:
Is this the best way to handle exceptions? Or should I do something different in my next projects?
Upvotes: 9
Views: 306
Reputation: 568
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. ");
}
}
Upvotes: -1
Reputation: 10136
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();
}
Upvotes: 3
Reputation: 1062810
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).
Upvotes: 6
Reputation: 960
The best answer you can get at Best Practices for Handling Exceptions
Upvotes: 2