开发者

Using "Throw" in a catchblock (and nothing else!) [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

difference between throw and throw new Exception()

I'm a programmer working on adding new functionality to legacy code. While debugging, I parsed over this Catch block, which got an angry "object not set to reference of object" notice from Visual Studio:

catch(Exception ex)
            {
          开发者_运维技巧      SporeLog.Log("Failed to create new SavedDocumentList with Name: " + name, ex);
                throw;
            }

What does it mean to "throw". I'm familiar with throw new [exceptiontype]... but what does it mean to just... throw ?

Is this good practice, or should I alter this code to ease the trials of the developers after me?

And why does Visual Studio yell at me for doing this?


Yes it is a good practice.... what it does is, it re-throws the same exception that it catched, keeping the stacktrace intact.


It means "re-throw this same exception". In other words, continue bubbling up the exception to the next try/catch block.

It's useful if you can't actually deal with an exception at this level, but want to log that the exception happened.

Unfortunately, many people think "log & rethrow" should be done at every level, leading to applications which run slowly, have log files with every exception logged multiple times, and often never actual handle the exception.


This is a good practice (sometimes). It allows you to catch an exception, log it or determine if it can be handled, then rethrow it without losing the StackTrace.

Your NullReferenceException came from SporeLog being null.


throw; rethrows the original exception. This allows you to take some action at the current level, and then propagate the exception up the stack.

If the exception is the result of an implementation detail, it may be more appropriate to use exception-chaining to throw a domain-specific exception that wraps the original exception, to hide your clients from implementation details, and a plethora different exception types to catch.

If the exception makes sense to your clients, then rethrowing it is fine practice.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜