Good use of try catch-blocks

clean codecode-qualityexceptionsreadability

I always find myself wrestling with this… trying to find the right balance between try/catching and the code not becoming this obscene mess of tabs, brackets, and exceptions being thrown back up the call stack like a hot potato.  For example, I have an app I'm developing right now that uses SQLite.  I have a Database interface that abstracts the SQLite calls, and a Model that accepts things to go in/out of the Database…  So if/when an SQLite exception occurs, it has to get tossed up to the Model (whom called it), who has to pass it off to whoever called the AddRecord/DeleteRecord/whatever…  

I'm a fan of exceptions as opposed to returning error codes because error codes can be ignored, forgotten, etc., whereas an Exception essentially has to be handled (granted, I could catch and move on immediately…)   I'm certain there's got to be a better way than what I've got going on right now.

Edit:  I should have phrased this a little differently.  I understand to re-throw as different types and such, I worded that poorly and that's my own fault.   My question is…   how does one best keep the code clean when doing so?   It just starts to feel extremely cluttered to me after a while.

Best Answer

Think of it in terms of strong typing, even if you aren't using a strongly typed language - if your method can't return the type you expected it to, it should be throwing an exception.

Also, rather than throwing the SQLException all the way to the model (or worse, UI), each layer should catch known exceptions and wrap/mutate/replace them with exceptions suited to that layer:

Layer      Handles Exception
----------------------------
UI         DataNotFoundException
Model      DatabaseRetrievalException
DAO        SQLException

This should help limit the number of exceptions you are looking for in each layer and help you maintain an organized exception system.

Related Topic