How can you do exception handling through multiple catch blocks in one case?

Say you have the following hierarchy. You have an Animal base class, with a bunch of subclasses like Cat, Mouse, Dog, etc.

Now we have the following scenario:

void ftn() { throw Dog(); } int main() { try { ftn(); } catch(Dog &d) { //some dog specific code } catch(Cat &c) { //some cat specific code } catch(Animal &a) { //some generic animal code that I want all exceptions to also run } } 

So, I want that, even if the dog was cast, I want the scene "Dog caught" to be performed, as well as the case of "Capture animals" to perform. How do you do this?

+6
source share
2 answers

Another alternative (besides trying to try in an attempt) is to isolate your common Animal processing code in a function that is called from any catch blocks you want:

 void handle(Animal const & a) { // ... } int main() { try { ftn(); } catch(Dog &d) { // some dog-specific code handle(d); } // ... catch(Animal &a) { handle(a); } } 
+9
source

AFAIK, you need to break this into two try-catch and rethrow blocks:

 void ftn(){ throw Dog(); } int main(){ try{ try{ ftn(); }catch(Dog &d){ //some dog specific code throw; // rethrows the current exception }catch(Cat &c){ //some cat specific code throw; // rethrows the current exception } }catch(Animal &a){ //some generic animal code that I want all exceptions to also run } } 
+7
source

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


All Articles