Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 244
jpbochi Avatar asked Sep 21 '10 14:09

jpbochi


People also ask

How are exceptions handled in C?

C doesn't support exception handling. To throw an exception in C, you need to use something platform specific such as Win32's structured exception handling -- but to give any help with that, we'll need to know the platform you care about. ...and don't use Win32 structured exception handling.

How does exception Work C++?

C++ exception handling is built upon three keywords: try, catch, and throw. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem.

Is there exceptions in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.

How do you handle exceptions in a program?

To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped. The catch block catches the exception and statements inside the catch block is executed.


2 Answers

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

like image 62
Richard Avatar answered Oct 04 '22 04:10

Richard


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

like image 27
David Pfeffer Avatar answered Oct 04 '22 05:10

David Pfeffer