views:

81

answers:

5

Hi,

just a general question, do you ALWAYS have to handle error?

i was just having this debate with one of my coworker where in his code I see a lot places where stuff are wrapped around a try statement and in the catch statement there is nothing.

I always thought it is a bad practice to not handling error or hide them from the user (except log them in the log file).

just want to know what other people thinks

thanks.

A: 

The practice of catching an exception and then "silencing it" is EVIL! i think 99.99% of all SOers will agree on that one.

Here's a very nice article from CodeProject on exception handling best practices. Guess what one of the sections is devoted to?

The worst thing you can do is catch (Exception) and put an empty code block on it. Never do this.

Any exception handling article worth its salt will mention the exception swallowing concept, and not to do it, in some way.

Paul Sasik
+1  A: 

If you can't handle the exception, then don't catch it. It may be that someone further up the call stack can properly handle it, and congratulations, you've now prevented them from doing their job <golfclap/>.

Ignacio Vazquez-Abrams
A: 

A lot of people around here have a what I call "it doesn't crash in my code" mentaility which leads to excessive catchs.

Personally, I think this is the wrong attitude, but for certain groups of people, a crash is just plain BAD regardless of how you try to make it sound good by saying "... at least I know there is a problem ..."

Dan
A: 

Only a Sith deals in absolutes. Seriously, though, I can think of at least one instance we ran across just recently where it was desirable to just drop it and move on. We recently implemented an in-house click tracking solution that sends an async AJAX request to an MVC controller to be logged. We don't care if it does not get logged and we don't want our own logs filling up with error logs that we don't want. so why bother with the overhead of doing anything in the catch block. We considered adding code in the catch block to at least increment a counter when we got an error, but there was no business reason for it at this time.

It really comes down to whether you are doing it out of laziness or because there is actually a good reason not to.

I'll probably get flack for saying that as it is bad practice in general. Do I get points for bravery?

Bradley Mountford
A: 

You have to handle the exception if there is something you can do with it


try
{
  //CODE
}
catch
{
  LogException();
  //and/or
  RollbackTransaction();
  //and/or
  ShowFriendlyMessageToUser();
  //and/or
  DoSomethingUsefullWithTheException();
  throw; //This is optional
}

This make no sense, but I've seen it a lot


try
{
  //CODE
}
catch
{
   throw;
}

EDIT 1 And you need a very good argument to put something like this. And probably you'll get fired anyway :-p


try
{
  //CODE
}
catch
{
   //HIDE TO THE WORLD THAT THIS IS FAILING
}
Claudio Redi