开发者

Rethrowing an exception from an exception catch

Is it a good idea to catch an exception and then throw another exception?

Like so:

Try
    ' Do operation xxx
Catch ex As Exception
    ' Operation xxx failed, need to execute cleanup
    ' But now I've caught this exception outside 开发者_如何学编程of my main control logic, 
    ' so I would like to re-throw it
    Throw New ApplicationException("XXX failed")
End Try

The reason for doing this is that while I catch my exception on a higher level logic (to make sure I can log it properly), I need to do some actions in the event of the exception that I can only do inside my class/function.

Can you think of any reasons/scenarios why this would be a bad idea?


Yes, this is a bad idea.

First of all, don't catch exceptions in order to execute cleanup. Use a Finally block for that, as it will be executed whether or not an exception occurred. You also don't need to throw a new exception just to say "XXX Failed". The stack trace will show that.

Second, do not use ApplicationException. Microsoft used to recommend that user-defined exceptions derive from ApplicationException, but that turned out to be a bad idea. They now recommend we just use Exception.

Finally, when you're going to throw a new exception because of an old one, be sure to include the old exception:

Throw New Exception("My new message", ex)


A few points. First, I agree with John Saunders on the use of finally. You really should be doing your cleanup there.

Second, if you want to throw a new exception then just either throw an exception or create your own exception type based on Exception. I would recommend doing this if you are catching a low level exception like I/O or SQL, and want to rethrow something specific to the operation that was being conducted. In this case you might want to nest the caught exception as the InnerException. Look for a constructor overload to do this easily.

Third, if you want to just rethrow I believe you can just write "throw", which implicitly throws the current exception that was caught. At least that is how you do it in C#, which lets the exception with its entire stack trace and other data continue bubbling up the stack intact.


It's not necessarily a bad idea. If a particular exception wouldn't make sense to callers of your method because it is related to low-level details that the callers don't know about, then it is a good idea to wrap the exception in a new exception that explains what the caller did wrong.

I would also like to add that 99% of the time you should catch specific exceptions instead of the general Exception type. If you catch all exceptions, you will most likely hide failures you aren't prepared to handle. It is better to let your program crash and tell you what went wrong that to be left wondering why your program isn't working quite right.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜