Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an error handler work internally?

I know that there has to be quite a lot of documentation about this topic on the internet. But doing research for hours without a proper answer is quite frustrating. So I assume I can't put my question in a good phrase. So here the full version:

I'm doing a presentation about try-catch, but it's rather boring to do the basic things. I know what try catch is and I know how it works. But here comes the magic: Let's assume I use C++.

The compiler will create a read only list on the heap with structures that give information about the functions in the try-block. That includes pointers for start and end of the routine, information about about the object type of the exception and so on. (Please correct me if I'm wrong)

Okay. Now an exception occurs. The so called error handler (here we go, who is the error handler?) will look up all the data about the failing routine and get the appropriate catch routine. The correct catch is found by comparing the exception object that is generated through the error with the exception objects in the catch.

For example: InvalidCastException (or something like that) is created. There is a catch for that, the error is handled and all objects that are created in the try block are destroyed.

But: How can the program notice that there is an exception? Is this handled by the program, by the runtime or maybe even by the processor (I read something about Ring0 and Ring1, different levels in the CPU oO).

like image 571
Haini Avatar asked Apr 21 '26 02:04

Haini


1 Answers

There are two ways of implementing exception handling in C++. First is to use Itanium ABI Zero-Cost exception handling. The second one is to use a pair of setjmp/longjmp to handle control flow for exceptions. The first is a preferred implementation for every modern compiler.

The program does not "listen" for exceptions, so it doesn't notice exceptions. Instead, it raises and processes them as part of the control flow. For example, "throw" is always raising an exception which triggers transfers the execution to exception handling code.

Even though these exceptions are heavily used in C++ which provides a nice interface to "throw" and "catch" them, they are also used in C, and even in the Linux kernel.

You can read more here:

  • http://sourcery.mentor.com/public/cxx-abi/abi-eh.html
  • http://llvm.org/docs/ExceptionHandling.html
  • Zero cost exception handling vs setjmp/longjmp