Can a function throw an exception of a derived class if its exception specification is of the base type?

I have the following code.

class Base{}; class Derived: public Base{}; class Test { public: void fun() throw(Base) { throw Derived(); } }; int main() { Test ob; ob.fun(); } 

Can fun () throw exceptions from derived types if the list of exception specifications is of the base type?

+4
source share
4 answers

Since Derived comes from Base , it technically is-a Base . So yes, you can call derived exception types if your method signature lists their base type.

But keep in mind that, as @MSalters writes, there are issues with exception specifications.

+3
source

Short answer: yes, maybe longer: Do not use function exception specifications. In the new standard C ++ 0x, it will be deprecated.

Why do they blame it? Because in the exception specification, C ++ does not work as in java. If you try to throw something else, you will not get any compilation error (e.g. in java). At run time, it will call the std::unexpected() function, which will call the unexpected handler function, which will terminate the program by default.

+3
source

Yes this good. A function allows an exception of type E if its exception specification contains type T , so that a handler for type T will correspond to an exception of type E (C ++ 2003 standard, 15.4)

+1
source

This is absolutely correct. Of course, this is possible, you can catch the exception by ref (base class) and, for example, throw it.

 //.. try { ob.fun(); } catch( Base& ex ) { // do something with the exception; // throw; // if you want it to be re-thrown } 
0
source

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


All Articles