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


November 2018


766 раз


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

    // Some code
catch (Exception e)

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

6 ответы


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.



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.


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.


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.


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


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.

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