Roland Weigelt

Born to Code

News

  • Meet me at:
     

     
  • I'm on Twitter:

  • English | Deutsch
  •  
    My .NET User Group:
     
  •  
    Personal homepage:
     
  •  
    XING:
     
    XING

.NET related Links

Archives

Why throwing an exception should be the exception

Alex writes about the impact of throwing an exception on performance and that it may not be as bad as one may assume. In the comments, people write that using exceptions for flow control is not the Right Thing to do.

Here’s my #1 reason why throwing an exception for flow control is definitely not a good idea: Debugging. When I’m debugging and I’ve set the debugger to “break on CLR exceptions” (and no, I don’t want to get more specific when I switch that option on and off dozens of times per day), I don’t want code execution to halt over and over again until I get to the actual problem.

It’s bad enough if some exceptions in non-exceptional situations cannot be avoided — I don’t need to introduce them in my own code.

Posted: Mar 29 2005, 01:58 PM by WeigeltRo | with 3 comment(s)
Filed under: ,

Comments

Oliver Sturm said:

Well, and apart from breaking into the debugger, it's close to impossible to understand the codeflow when trying to step through code that throws exceptions. It's always a surprise to find the next line in some far-away catch block after hitting F10.

Thanks for that additional argument. I wrote my own blog entry on the same topic yesterday, but forgot about debugging :-)
# March 30, 2005 3:51 AM

S Dot One said:

The cause of the fact that debugging is hard to do is just because you don't have a way to see what kind of exceptions you can expect.
Normally you'd write unit test, which tests all kind of expected exceptions, this makes you understand the code a lot better. And at the same time shows up bad design in the underlying code.
# March 30, 2005 8:53 AM

Roland Weigelt said:

While unit testing reduces the amount of manual debugging necessary dramatically (as I have witnessed in the past 18 months I have developed mostly test-driven), there *are* situations where you have a large system that throws an *unexpected* exception. I'm an experienced developer, but I'm also a mere mortal and given a finite amount of time, I'm not always able to think of every possible thing that can go wrong and cover it in a unit test.

So when something unexpected happens, it's worth a lot when you are able to reproduce the situation running the program in the debugger and quickly find the place and the context of the problem.

Where TDD has changed my mindset is that I now tend to reproduce the situation in a unit test rather than make a change, debug, find out the problem wasn't fixed, make another change, debug again, and so on.
# March 30, 2005 12:37 PM