Alex Rivera | Logout

Should I catch exceptions only to log them?

Asked 2008-09-18T18:44:30.830
31

Should I catch exceptions for logging purposes?

public foo(..)
{
   try
   {
     ...
   } catch (Exception ex) {
     Logger.Error(ex);
     throw;
   }
}

If I have this in place in each of my layers (DataAccess, Business and WebService) it means the exception is logged several times.

Does it make sense to do so if my layers are in separate projects and only the public interfaces have try/catch in them? Why? Why not? Is there a different approach I could use?

Edit
Report

3 Answers

20

Unless you are going to change the exception, you should only log at the level where you are going to handle the error and not rethrow it. Otherwise your log just has a bunch of "noise", 3 or more of the same message logged, once at each layer.

My best practice is:

  1. Only try/catch in public methods (in general; obviously if you are trapping for a specific error you would check for it there)
  2. Only log in the UI layer right before suppressing the error and redirecting to an error page/form.
answered 2008-09-18T18:48:42.583
1

Use your own exceptions to wrap inbuild exception. This way you can distinct between known and unknown errors when catching exception. This is usefull if you have a method that calls other methods that are likely throwing excpetions to react upon expected and unexpected failures

answered 2008-09-18T18:49:23.377
0

My method is to log the exceptions only in the handler. The 'real' handler so to speak. Otherwise the log will be very hard to read and the code less structured.

answered 2008-09-18T18:53:01.387

Your Answer