How to refactor use of the general Exception?

Posted by Colin on Stack Overflow See other posts from Stack Overflow or by Colin
Published on 2010-04-20T05:54:47Z Indexed on 2010/04/20 6:03 UTC
Read the original article Hit count: 408

Our code catches the general exception everywhere.

Usually it writes the error to a log table in the database and shows a MessageBox to the user to say that the operation requested failed. If there is database interaction, the transaction is rolled back.

I have introduced a business logic layer and a data access layer to unravel some of the logic. In the data access layer, I have chosen not to catch anything and I also throw ArgumentNullExceptions and ArgumentOutOfRangeExceptions so that the message passed up the stack does not come straight from the database.

In the business logic layer I put a try catch. In the catch I rollback the transaction, do the logging and rethrow.

In the presentation layer there is another try catch that displays a MessageBox.

I am now thinking about catching a DataException and an ArgumentException instead of an Exception where I know the code only accesses a database.

Where the code accesses a web service, then I thought I would create my own "WebServiceException", which would be created in the data access layer whenever an HttpException, WebException or SoapException is thrown.

So now, generally I will be catching 2 or 3 exceptions where currently I catch just the general Exception, and I think that seems OK to me. Does anyone wrap exceptions up again to carry the message up to the presentation layer?

I think I should probably add a try catch to Main() that catches Exception, attempts to log it, displays an "Application has encountered an error" message and exits the application. So, my question is, does anyone see any holes in my plan? Are there any obvious exceptions that I should be catching or do these ones pretty much cover it (other than file access - I think there is only 1 place where we read-write to a config file).

© Stack Overflow or respective owner

Related posts about c#

Related posts about best-practices