20

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?

Community
  • 1
  • 1
jpbochi
  • 4,366
  • 3
  • 34
  • 43

2 Answers2

4

.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++).

Community
  • 1
  • 1
Richard
  • 106,783
  • 21
  • 203
  • 265
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.

David Pfeffer
  • 38,869
  • 30
  • 127
  • 202