I have asked a few questions on here and read a few articles around exception handling but don’t think I’m really grasping when you should and when you shouldn’t handle an exception. From the articles I’ve read it states to “only handle exceptions you can recover from” What does it mean by that. If I can’t handle the exception what do I do? Let it propagate back up the stack? If I don’t handle it how can I log it and present a user friendly error message. What do most people do in web apps and web services?
As an example say I have a lower tier data layer that pulls data from sql
try{
//do something with db
}catch(SqlException ex){
//what should i do here
//should i call code again to retry getting data from db
}catch(Exception ex){
//should i even catch exception of type exception
}
How do I handle exceptions in lower tiers? Should I just let the exception bubble up the tiers? If so then if I want to catch an exception of type sqlexception then I need a reference to the library sqlexception is part of but surely I shouldn’t have to reference that library in a layer that has nothing to do with data access.
Exception management is a large subject, so I’ll only touch the surface here.
If you don’t know how to recover from a specific exception, then there’s not usually any point in catching it. If it’s a web app or service, the web server itself will deal with the logging and recovery.
In some cases, you need to catch exceptions so that you can a generic recovery, for example by cancelling or reversing a transaction. In that case, an acceptable approach is to
catch the exception, do the generic recovery, and then throw the exception again.
Yes.
The web server will log the exception. If you want to present a user-friendly error message in a web app, you can catch/log at the highest level of the stack and re-direct to your error message. Again, I would try not to catch System.Exception – instead make a list of the exceptions that your app throws, and catch just these types before presenting a message tailored to each type. As the list of exception types grows, either prevent each new exception type by changing the code, or add a new catch for that exception type.
In a web service, you can create a custom exception and add that as a node to the generic exception that the web service will provide.
In your code example, I wouldn’t use try…catch unless you’re expecting an exception and you know what to do with it.
Yes.