开发者

Error handling with try catch (AGAIN)

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 the开发者_Go百科re 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.


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/>.


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.


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?


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜