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

人走茶凉 提交于 2020-01-28 16:10:48

问题


Identical to "How do exceptions work (behind the scenes) in C++", but for 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.

How does .NET handles these operations? How does the mapping for the "current" handlers work? How much code is emitted in a try/catch block? And in a throw block?


回答1:


Read Christopher Brumme's article; it gives a very detailed explanation of what happens behind the scenes in CLR exception handling:

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




回答2:


.NET exceptions on Windows use the OS' underlying Structured Exception Handling (SEH) mechanism, in the same way as native code. As listed in the linked question for C (and C++).




回答3:


.NET exceptions use the underlying Windows structured exception handling implementation, though this is not a requirement. 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.



来源:https://stackoverflow.com/questions/3761446/how-do-exceptions-work-behind-the-scenes-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!