Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I catch exceptions only to log them?

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?

like image 564
Xerx Avatar asked Sep 18 '08 18:09

Xerx


People also ask

When should you catch exceptions?

You generally throws an exception when you want to notify the caller of the method of some failures. Show activity on this post. As others have said, as a general rule, you should catch an exception when you can actually handle it, otherwise, just throw it.

Is it good practice to catch exception?

The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.


2 Answers

Definitely not. You should find the correct place to handle the exception (actually do something, like catch-and-not-rethrow), and then log it. You can and should include the entire stack trace of course, but following your suggestion would litter the code with try-catch blocks.

like image 51
ripper234 Avatar answered Sep 20 '22 20:09

ripper234


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.
like image 40
Guy Starbuck Avatar answered Sep 22 '22 20:09

Guy Starbuck