Exception Handling

Posts   
 
    
MikeP
User
Posts: 40
Joined: 27-May-2007
# Posted on: 12-Dec-2007 13:56:54   

Good Afternoon All,

I am currently pondering over the best exception handling approach for some of my business objects. These objects all return EntityColletions<T> according to a RelationPredicateBucket which is passed to them.

Generally I would like to catch all exceptions caused by database operations and stop the program from crashing. I would however like to inform the user of the reason the requested operation was unsuccessful.

There are two different approaches I can see at the moment:

Wrapping the Collection in a wrapper class which includes a bool returning true if an error occurred as well as the exception itself if thrown. This class is passed to the calling object and dealt with accordingly.

Or

Let the exception bubble up into the calling object and deal with it there (outside the business layer).

Any opinions on what would be preferable? Also at the moment I am catching two exceptions: SqlClient.SqlException and ORMSupportClasses.ORMException. Will these two exception cover all database operations?

Regards,

Mike

jmeckley
User
Posts: 403
Joined: 05-Jul-2006
# Posted on: 12-Dec-2007 15:12:35   

i have read that you should only catch exceptions you expect. like parse a number from a string. in this case you could expects that a formatexception may be thrown. (bad example because i would use. int.tryparse() instead, but you get the idea.)

unless you know you have connectivity/UC/PK/Concurrency problems I wouldn't catch them. if you do catch them, I would wrap the exception in a user friendly exception and rethrow. then catch the exception in the presentation.

try
{
    adapter.Save(MyEntity);
}
catch(OrmException e)
{
    throw new MyPrettyDBException(e);
}


public class MyPrettyDBException : Exception
{
    public MyPrettyDBException(Exception e)
        : base ("Could not save the data.", e)
    {
    }
}
MikeP
User
Posts: 40
Joined: 27-May-2007
# Posted on: 12-Dec-2007 19:29:55   

Thanks for your thoughts.

I do agree with the concept of not catching all errors, only the ones you want to recover from. This is the case in my application where I do not want it to terminate because of a database operation problem (i.e. the application is still useful to the user even if the database is down etc.).

Having thought about it a bit more I think you are right with regards to rethrowing the exception and handling the rest in the UI layer.

Mike