开发者

Rethrowing exception

开发者 https://www.devze.com 2023-02-24 04:41 出处:网络
I开发者_运维技巧 see a lot of code like: try { // Some code } catch (Exception e) { throw; } Why would someone need to catch and rethrow an exception with nothing else in the catch block?No reason,

I开发者_运维技巧 see a lot of code like:

try
{
    // Some code
}
catch (Exception e)
{
    throw;
}

Why would someone need to catch and rethrow an exception with nothing else in the catch block?


No reason, unless you wanted to throw a different type of exception or perform some actions prior to re-throwing.


Such code could be required to avoid strange effect of exception filters. For details see http://www.pluralsight-training.net/community/blogs/keith/archive/2005/03/31/7149.aspx (link found by Brian in Why catch and rethrow an exception in C#? thread).

Short version - there could be someone elses code run between the moment exception is throw and catch block. As result that code may be able to access some information that is not intended to be visible (i.e. like in the article's sample allowing to run third party code in impersonated context).

This is important for public libraries and code that allows third party plugins, generally not a concern for application developers.


My guess is that it's just for debugging purposes - the developer can set a breakpoint on the throw statement and then examine what's in e.


It could be that the person wants to explicitly denote that this section of code may throw an exception (as a sort of documentation) and, in the future, may wish to handle the exception in a different manner, thus they would build the structure in now.

Strictly speaking, it essentially does nothing, though.


Normally you'll see a structure like this during development, where the developer is using a try-catch but is yet to implement the catch.


C# has provided a very simple syntax to provide the needed rethrowing semantics all along, but it seems not very people know about it. This left me puzzled, since it's essentially the same syntax used by C++: an empty throw statement.

http://winterdom.com/2002/09/rethrowingexceptionsinc

0

精彩评论

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