Why does catching a base class block break an exception when I throw an object of a derived class?

If I pass an object to a derived class, then the catch block of the derived class is called. But the conclusion suggests that the exception falls into the base class. What for?

#include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; // some other stuff try { // Some monitored code throw d; } catch(Base b) { cout<<"Caught Base Exception"; } catch(Derived d) { //This catch block is NEVER executed cout<<"Caught Derived Exception"; } getchar(); return 0; } 
+6
source share
3 answers

The standard says (see [except.handle] / 4 ] of the working draft as an example, my hit):

Handlers for the try block are checked in order of appearance. [Note. This allows you to write handlers that can never be executed , for example, by placing the handler for the final derived class after the handler for the corresponding unambiguous public base class .

This is exactly what you did in your code.
Therefore, I would say that the intended behavior, regardless of your expectations.

Note that you can swap two handlers to solve the problem.

+10
source

Little can be said about this.

First, it is recommended to catch exceptions by reference instead of value. This prevents slicing the exception object if it is received. This does not apply to exceptions, but is a common characteristic of inheritance.

A description of this phenomenon is discussed here.

Also, as pointed out in another answer, if you insist on doing so, you need to reorder the catches, since the derived class satisfies the catch base block. There is another way to do this, although it explicitly uses this property: just the base class will catch everything. You can use this if there is no particular feature of a derived exception that needs to be handled separately.

+3
source

Catch calls are checked in order - you get the first match, not the best match.

Thus, checking the derived type will first force this.

+1
source

Source: https://habr.com/ru/post/1013875/


All Articles