Повторное выбрасывание исключения

Обновить

November 2018

Просмотры

766 раз

1

Я вижу много кода, как:

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

Зачем кому-то нужно, чтобы поймать и повторно выдать исключение ни с чем-либо в блоке поймать?

6 ответы

0

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

1

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.

1

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.

0

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.

3

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

0

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.

Связанные вопросы