tags:

views:

758

answers:

10

Been having a "heated debate" with a colleague about his practice of wrapping most of his functions in a try/catch but the catch has JUST a "throw" in it e.g.

Private sub foo()
    try
        'Do something'
    catch
        throw 'And nothing else!'
    End Try
End Sub

My thought was to not even bother (assuming you don't need to do anything at this point) - the exception would bubble to the next exception handler in a parent member.

The only argument that sounded plausible was that sometimes exceptions weren't caught and your code stopped (in debug mode) with the current line highlighted in green...and that this may be something to do with multiple threads? Best practice does state "an exception handler for each thread" but mostly we work single-threaded.

The good thing may be it could be useful in debug mode to not suddenly pop out to a parent member (yes, Joel!) - you'd move to the "throw" statement and be able to examine your locals. But then your code would be "littered with try/catch/throws" (to quote another thread here)?

And what sort of overhead would be involved in adding try/catch/throws everywhere if no exception occurs (i.e. should you avoid try/catches in tight loops)?

+14  A: 

The reason you have a lone throw inside a catch rather than throwing a new exception is because this causes the original stack trace/exception data to be preserved. And one reason you might do this is because you can now set a break-point there for debugging.

Joel Coehoorn
Another reason to rethrow is to clean up existing state - it's like saying, "OK, I know something bad happened. *I* can't handle it, but I'll clean up before I leave it to someone else. Sometimes finally is NOT the right place for this.
plinth
While a lone throw will preserve state, so will not catching the exception at all. If you want to set a breakpoint for debugging, set a breakpoint from Debug > Exceptions. A catch clause is totally unnecessary.
Dour High Arch
@DHA: Please explain how you'd catch an exception at a precise level in a call stack which may be 20 levels deep then.
Jon Skeet
He means, you should enable automatic breaks at any occurence of a given exception, which you can enable in the debug->exceptions menu.
Jan
You can break when it's thrown, but it can then be a pain to backtrack up the stack the right amount. I'm not saying it's common to want to do this, but it does happen.
Jon Skeet
(And the other thing is that the same exception may be thrown from many other places.)
Jon Skeet
+6  A: 

I would only ever do this while debugging an issue - and I'd remove the code again before checking in. It can occasionally be handy to put a breakpoint in to stop at a particular stack level if an exception is thrown. Beyond that though - no.

Jon Skeet
Definitely don't code it like that by default. But if I need to add that during a debugging session, I'd probably leave it in. If I needed it once I likely will again, and it's a subtle way to tell other developers that the included code may be more difficult than it appears.
Joel Coehoorn
I'd put that in a comment then, rather than leaving ugly and distracting code. Most of the time when that code needs to be read, it probably *won't* be the same sort of situation - so don't make it more complex for that case.
Jon Skeet
I do not think it is a good idea to test something, then change the code "before checking in".
Dour High Arch
I wouldn't do it *just* before checking in. I would use the debugger to work out what was going wrong; write a failing unit test; take out the try/catch/throw and prove it's still going wrong; fix it and see it all go green; submit for code review; check in. Do you never remove anything from code?
Jon Skeet
Man after my own heart, Dour High Arch! Banging heads with a young 'un now about that...any change is a new risk!!Conditional IF's I find useful but just as dangerous.
AndrewD
+1  A: 

Doing it always by default looks like bad design. But there might be reasons for catching and throwing, for example it you want to throw a different exception.

Fabian Buch
If you're throwing a different exception, it's not the situation described by the OP. He's specifically talking about the "bare throw" situation.
Jon Skeet
Then I don't know a reason for it, since for debugging there are debuggers.
Fabian Buch
+5  A: 

In practice, my thought is, if you don't intend to handle the error, don't catch it.

Geoff
+15  A: 

Microsoft recommends not to catch an exception when the only thing you do is to rethrow it immediately (i dont remember the source for now). Your code should only catch exceptions that you want to handle for clean up things or similar actions.

So generally its not a good practice to catch and rethrow an exception.

Reasons for catching and replacing it with another exception might be

  • Logging
  • Hiding sensitive information from the caller (Stacktrace, exception details)

And for debugging you might want to change your "Break when an exception is:"-Handler (Press Ctrl+Alt+e) the value "thrown" on selected CLR Exceptions.

You might want to take a look at the entlib exception handler block (EHB), with which you can establish a pattern on how to deal with exceptions in your code.

Regarding your question on performance i think its not a propblem to have many try/catch blocks in your code but you will get performance hits when your code raises and catches many exceptions.

Jan
Thanks for the Ctrl+Alt+e tip (you need an active code pane though)...can't find that in the main menu system (I'd expect it under Tools->Options...Debugging).
AndrewD
Normally you'll find it under menu Debug->Exceptions, when a project is loaded and a code window is active.
Jan
VS2005 doesn't seem to have that...but it does the Ctrl+Alt+E!?Must upgrade :-(
AndrewD
Cant tell you, because i have deinstalled VS2005 :)
Jan
+1  A: 

Yes, it's handy for putting a breakpoint in the catch.

An alternate and cleaner way is to breakpoint in the constructor of the object you're throwing. You're seeing the program state at a point closer to the source of the error.

Mark Ransom
+1  A: 

You do not need a catch clause to catch exceptions in the Visual Studio debugger. Choose Debug > Exceptions, and select which exceptions you want to catch, all of them if necessary.

Dour High Arch
That won't help you catch them at a particular level of the stack though, which can often be handy.
Jon Skeet
A: 

If you catch an exception and replace it with another exception, you should typically wrap the original exception in the new one. This is usually done by passing the old exception into the new one's constructor. That way you can dig in as much as necessary to figure out what happened. The main case when you wouldn't is when you need to hide data for security reasons. In these cases, you should try to log the exception data before you clear it out.

The rationale I have seen for wrapping exceptions with new ones, rather than just letting them bubble up the stack, is that exceptions should be at the same symantic level as the methods they are coming from. If I call AuthenticateUser, I don't want to see an SQL exception. Instead, I should see some exception whose name tells me the authentication task could not be completed. If I dig into this exception's inner exceptions, I could then find the SQL exception. Personally, I am still weighing the pros and cons of doing this.

Neil Whitaker
A: 

Since there is zero error handling, this catch is useless. If there was logging or some cleanup done sure, but in this situation I'd get rid of the try/catch.

Bryan
A: 

This can also be useful if you need to inspect something about the exception, and do something for one circumstance or throw it for other circumstances. For instance, if you need to inspect the error number in a SQLException. You can perform a certain action if the error number is one you're prepared to handle. For others you can simply "throw" it so the stack trace is preserved, as mentioned above.

NYSystemsAnalyst