What is the suggested approach or best practice for handling exceptions in tiered applications?
- Where should you place
try/catch
blocks?
- Where should you implement logging?
- Is there a suggested pattern for managing exceptions in n-tiered applications?
Consider a simple example. Suppose you have a UI, that calls a business layer, that calls a data layer:
//UI
protected void ButtonClick_GetObject(object sender, EventArgs e)
{
try {
MyObj obj = Business.GetObj();
}
catch (Exception ex) {
Logger.Log(ex); //should the logging happen here, or at source?
MessageBox.Show("An error occurred");
}
}
//Business
public MyObj GetObj()
{
//is this try/catch block redundant?
try {
MyObj obj = DAL.GetObj();
}
catch (Exception ex) {
throw new Exception("A DAL Exception occurred", ex);
}
}
//DAL
public MyObj GetObj()
{
//Or is this try/catch block redundant?
try {
//connect to database, get object
}
catch (SqlException ex) {
throw new Exception("A SQLException occurred", ex);
}
}
What criticisms would you make of the above exception handling?
thanks
My rule of thumb is generally to catch exceptions at the top level and log (or otherwise report) them there, because this is where you have the most information about the the error - most importantly the full stack trace.
There may be some reasons to catch exceptions in other tiers, however:
- The exception is actually handled. Eg. a connection failed, but the tier re-tries it.
- The exception is re-thrown with more information (that isn't already available from looking at the stack). Eg. the DAL might report which DB it was trying to connect to, which
SqlException
wouldn't tell you.
- The exception is translated into a more general exception that is part of the interface for that tier and may (or may not) be handled higher up. Eg. the DAL may catch connection errors and throw a
DatabaseUnavailableException
. The BL may ignore this for operations that are not critical or it may let it propogate for those that are. If the BL caught SqlException
instead it would be exposed to the implementation details of the DAL. Instead the possibility of throwing DatabaseUnavailableException
is part of the interface of the DAL.
Logging the same error at multiple tiers is generally not useful, but I can think of one exception: when a lower tier doesn't know whether a problem is critical or not it can log it as a warning. If a higher tier decides that it is critical it can then log the same problem as an error.
Here are a few rules I follow related to exception handling:
- exceptions should only be caught in the layers that can implement the logic for handling them. Most of the cases this happens in the upmost layers. As a rule of thumb, before implementing a catch inside a layer, ask yourself if the logic of any of the upper layers depends in any way on the existence of the exception. For example in your business layer you might have the following rule: load data from an external service if the service is available, if not load it from the local cache. If calling the service throws an exption you can catch and log it at BL level and then return the data from the cache. The upper UI layer does not have to take any action in this case. However, if both the service and the cache call fail the exception would have to go to the UI level so that an error message can be displayed to the user.
- all exceptions inside an application should be caught and if there is no special logic for handling them, they should be at least logged. Of course, this does not mean that you have to wrapp the code from all methods in try/catch blocks. Instead any application type has a global handler for uncaught exceptions. For example in Windows Applications the
Application.ThreadException
event should be implemented. In ASP .Net applications the Application_Error
event handler from global.asax should be implemented. These places are the upper most locations where you can catch exceptions in your code. In many applications this will be the place where you will catch most of the exceptions and besides logging, in here you will probably also implement a generic and friendly error message window that will be presented to the user.
- you can implement try/finally functionality where you need it without implementing a catch block. A catch block should not be implemented if you do not need to implement any exception handling logic. For example:
SqlConnection conn = null;
try
{
conn = new SqlConnection(connString);
...
}
// do not implement any catch in here. db exceptions logic should be implemented at upper levels
finally
{
// finalization code that should always be executed.
if(conn != null) conn.Dispose();
}
- if you need to rethrow an exception from a catch block do that by simply using
throw;
. This will ensure that the stack trace is preserved. Using throw ex;
will reset the stack trace.
- if you need to rethrow an exception with another type that would make more sense for the upper levels, include the original exception in the InnerException property of the newly created exception.
- if you need to throw exceptions from your code use meaningful exception types.
The first thing to fix would be to never throw a general Exception
.
The second, unless there's really a good reason to wrap an exception, just have throw;
instead of throw new...
in your catch clause.
The third (and this isn't a hard & fast rule), don't catch general Exceptions at any point below the UI layer. The UI layer should catch general Exceptions so that a user-friendly message can be displayed to the end user, not the technical details of what blew up. If you catch a general exception deeper in the layers it's possible for it to be swallowed unintentionally and makes for bugs that are quite difficult to track down.
Exception handling is difficult in any application. You need to think about each and every exception and quickly get into a pattern that works for you. I try and group exceptions into one of the following categories...
- Exceptions that should only happen if your code is wrong (or you don't understand, or you don't have control over them):
Example: Maybe your persistence framework requires you to catch SQL exceptions that could arise from malformed SQL, however, you're executing a hard coded query.
Handling: In my experience most exceptions fall in this category. At the very least, log them. Even better, send them to an exception handling service which logs them. Then in the future if you decide you want to log them differently or do something differently with them you can change it in one place. Maybe you also want to send a flag up to the UI layer saying that some kind of error occurred and they should retry their operation. Maybe you mail an administrator.
You will also need to return something to the higher layers so that life on the server goes on. Maybe this is a default value, or maybe this is null. Maybe you have some way of canceling the entire operation.
Another choice is to give the exception handling service two handling methods. A handleUnexpectedException()
method would notify the user but not rethrow an exception and you could then return a default value if you have the ability to unwind the stack yourself or continue on in some way. A handleFatalException()
method would notify the user and rethrow some kind of exception so that you can let the exception throwing unwind the stack for you.
- Exceptions that are actually caused by the user:
Example: The user is trying to update a foobar widget and give it a new name, but a foobar widget already exists with the name they want.
Handling: In this case you need to get the exception back to the user. In this case you can go ahead and keep throwing the exception (or better, don't even catch it) until it reaches the UI layer and then the UI layer should know how to handle the exception. Make sure to document these exceptions so that you (or whomever is writing your UI) is aware that they exist and knows to expect them.
- Exceptions that you can actually handle:
Example: You make a remote service call and the remote service times out but you know they have a history of doing so and you should just redo the call.
Handling: Sometimes these exceptions start off in the first category. After your application has been in the wild for a while you realize that you actually have a good way to handle it. Sometimes, like with exceptions from optimistic locking or interrupted exceptions, catching the exception and doing something with it is just a part of business. In these cases, handle the exception. If you're language (I'm thinking Java) distinguishes between checked and unchecked exceptions I would recommend these always be checked exceptions.
To address your above question I would delegate the initial exception to a service that would notify the user and depending on what kind of object MyObj is (e.g. settings) I might let this be a non-fatal exception and return a default value or if I can't do that (e.g. user account) then I might let this be a fatal exception so I don't have to worry about it.
I am with sepearate exception Class for each layer (DALException,BLException,...) to log (e.g: in file) the exceptions at the layer boundaries (this is for administrator) ,because user only should see clear and understandable error message. those exception should deal with on DAlBase which inherirted by all Data access layer calsses an so on all layers. with that we can centralize the exception handling in few class and the developer will only throw layerexception (e.g: DALException)
see more information MultiTier Exception Handling.