Catching vs. Bubbling Errors

When should you catch an error? When should you just bubble up an error? I was asked this question a while back and came to a rather simple answer. There are two cases when you should catch an error. In all other cases, bubble it.

When the error needs to be displayed or logged, catch it

When you need to do something with the error, you should catch it. For instance, in the UI, you need to display errors to the user. Bubbling it up would mean that it would become an unhandled error, so it needs to be handled. Catch it here so you can do something graceful rather than crash the app.

When you can add additional information about the error, catch it

When a method can add some value to the error message that will help the end user or developer understand what is going on, do so. A good example would be if a sql statement failed, it would be useful to catch the error and add the sql that failed to the error message along with any parameters that may have caused the failure. Then throw a a new error with this message and set its InnerException property to the original error.

Let the error bubble up in other cases

I can’t think of any other reason to catch the error, so just let it on through and bubble up in any other instance.

-Chris

This entry was posted in .NET, Error Handling and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*
*