How is C ++ exception handling related to classes derived from exception?

If I catch a BaseException , will they also throw exceptions from BaseException ? Does handling of exceptions with regard to inheritance, etc. Or does it only correspond to the fact that a particular type of exception has been selected?

 class MyException { ... }; class MySpecialException : public MyException { ... }; 

 void test() { try { ... } catch (MyException &e) { //will this catch MySpecialException? } } 
+4
source share
5 answers

Easy to explain with code: http://ideone.com/5HLtZ

 #include <iostream> class ExceptionBase { }; class MyException : public ExceptionBase { }; int main() { try { throw MyException(); } catch (MyException const& e) { std::cout<<"catch 1"<<std::endl; } catch (ExceptionBase const& e) { std::cout<<"should not catch 1"<<std::endl; } //////// try { throw MyException(); } catch (ExceptionBase const& e) { std::cout<<"catch 2"<<std::endl; } catch (...) { std::cout<<"should not catch 2"<<std::endl; } return 0; } 

Output:
catch 1
catch 2

+3
source

C ++ exception handling will correspond to subclasses of exceptions. However, it does a linear search from the first catch () to the last and will only match the first. Therefore, if you intend to catch Base and Derived, you first need to catch (MySpecialException &).

+5
source

Yes, it will be very common. Usually, for example, catch std::exception , although the exception std::bad_alloc is likely to be a derived exception of the type std::bad_alloc or std::runtime_error .

You can catch the base type and the derived one, and they will be caught in turn, but you must first catch the derived type.

 try { // code which throws bad_alloc } catch ( const std::bad_alloc & e ) { // handle bad_alloc } catch ( const std::exception & e ) { // catch all types of std::exception, we won't go here // for a bad_alloc because that been handled. } catch ( ... ) { // catch unexpected exceptions throw; } 
+2
source

Yes, it will catch exceptions received from the database.

0
source

turn on

class ExceptionBase {};

class MyException: public ExceptionBase {};

int main () {try {throw MyException (); } catch (MyException const & e) {std :: cout <"catch 1"

 //////// try { throw MyException(); } catch (ExceptionBase const& e) { std::cout<<"catch 2"<<std::endl; } catch (...) { std::cout<<"should not catch 2"<<std::endl; } return 0; 
0
source

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


All Articles