简体   繁体   English

C#中的异常如何工作(在幕后)

[英]How do exceptions work (behind the scenes) in C#

Identical to " How do exceptions work (behind the scenes) in C++ ", but for C# . 与“ 异常如何在C ++中(在后台)工作 ”相同,但对于C#

I know that the steps below have to be performed when an exception is thrown. 我知道抛出异常时必须执行以下步骤。

  1. Find the nearest handler for the exception type; 查找最接近异常类型的处理程序;
  2. Unwind the stack up to the handler level; 将堆栈展开到处理程序级别;
  3. Call the handler; 调用处理程序;
  4. Find and call every finally blocks. 查找并调用每个finally块。

How does .NET handles these operations? .NET如何处理这些操作? How does the mapping for the "current" handlers work? “当前”处理程序的映射如何工作? How much code is emitted in a try/catch block? 在try / catch块中发出多少代码? And in a throw block? 然后扔在一块?

Read Christopher Brumme's article; 阅读Christopher Brumme的文章; it gives a very detailed explanation of what happens behind the scenes in CLR exception handling: 它提供了有关CLR异常处理的幕后操作的非常详细的解释:

http://blogs.msdn.com/b/cbrumme/archive/2003/10/01/51524.aspx http://blogs.msdn.com/b/cbrumme/archive/2003/10/01/51524.aspx

.NET exceptions on Windows use the OS' underlying Structured Exception Handling (SEH) mechanism, in the same way as native code. Windows上的.NET异常使用操作系统的基础结构化异常处理 (SEH)机制,与本地代码相同。 As listed in the linked question for C (and C++) . 如在C(和C ++)链接问题中列出的。

.NET exceptions use the underlying Windows structured exception handling implementation, though this is not a requirement. .NET异常使用底层Windows结构化异常处理实现,但这不是必需的。 Mono may do it differently. 单声道可能会有所不同。

In fact, if you write a single-line Console app that just throws an exception, and then run it in Windbg, you'll see the hook into the unmanaged exception handling. 实际上,如果编写一个仅引发异常的单行控制台应用程序,然后在Windbg中运行它,您将看到非托管异常处理的钩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM