Thursday, April 10, 2008

How to to effective error handling using Exceptions

I've never actually grasped enough how to work with Exceptions. It was a mystery for me when to throw them and when to catch them. Lately, i have done some improvisation with the code, and I got some new ideas.



As far as I know there are two main approaches to error handling.


  1. One is c/c++ style, where error codes are returned with return codes and optionally passing aditional info in other parameters

  2. Second approach is to throw and catch Exceptions





To begin working with exceptions effectively one must first decide which way to go. Exceptions and error codes can not go together, as this will make the code spaghetti like, and people will get confused. Important thing is to remember is that code is for people, not for machines




My preference is to go Exceptions way, for these reasons:


  1. Exceptions allow you indicate an error in any place, and error handling can occur in any other place

  2. Using error codes forces every function to also return an error code, which is very intrusive. Error handling should not force you to change your existing or new code in any way.

  3. Exceptions can be catched on a very high granularity (having that there is a proper exception hierarchy). One can catch internal errors in service layer, and UI related exceptions in UI layer

  4. Exceptions can be used to carry a very brief error message, and, what is even more important, information how to solve the problem

  5. Exceptions can even be catched, stuffed with more detailed exception text (for example context-specific information) and rethrown again


No comments: