Search code examples
exception

n-layer using try catch


I'm working on an n-tier application, and doing try/catch only in my presentation layer. If an error occurs in the data layer or business layer, this error is captured by the try/catch in my presentation layer. Is this good, or should I work with try catch in every method of each layer?


Solution

  • Here's what you want to avoid at any level: a bunch of methods that all look like this:

    void method()
    {
       try 
       {
          // some code here that may potentially throw an exception
       }
       catch ( /* anything here */)
       {
          // code right here to handle that exception
       }
    }
    

    If that's what you're doing, you may just as well go back to VB's old On Error Goto system, because you haven't gained anything. Exceptions provide two major advantages for error handling: the ability to easily handle different types of errors in different ways, and the ability for errors to be caught further up in the program's call stack. It's the second advantage that you're asking about here.

    So we see that you do want to allow exceptions to "bubble up" to higher layers, as it's a big part of why we have exceptions at all... but do you always want to handle them at the presentation layer? No, we can do better. Sometimes, there may be business rules about how to respond to certain exceptions from the data layer. Sometimes, the data layer itself may be able to handle and recover from an exception without alerting the layer above it.

    Additionally, an advantage of exceptions is that it can leave you to write simpler code in the lower layers, with fewer breaks from the normal flow of program execution for error handling code. This comes at the price of instead placing more of try/catch in the presentation tier. Again, this doesn't mean the presentation tier is the only place to handle them, but this is the place to make the effort to ensure they don't get past your presentation layer un-caught. If you can't handle them anywhere else, do have a way to catch them in the presentation layer and show them to the user in a friendly way. It's also a good idea to use the the same mechanism to log or report your exceptions, so you can get good metrics on where your application fails, and then use that information to make the application better.

    When you do get to the point you're inside a last-ditch exception handler, you may also want to consider terminating the application. If you really have unexpected things going on, such that unhandled exceptions make it through the presentation tier, there's a valid school of thought that suggests it may not be a good idea to continue running the program. But even in this case, you'll want to catch and try to report the exception, and then crash as gracefully as possible.