Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Catching base and derived classes as exceptions

  • Difficulty Level : Easy
  • Last Updated : 29 Jun, 2021
Geek Week

Exception Handling – catching base and derived classes as exceptions:
If both base and derived classes are caught as exceptions then catch block of derived class must appear before the base class. 
If we put base class first then the derived class catch block will never be reached. For example, following C++ code prints “Caught Base Exception” 
 

C




#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;
}

In the above C++ code, if we change the order of catch statements then both catch statements become reachable. Following is the modified program and it prints “Caught Derived Exception”
 

C




#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(Derived d) {
        cout<<"Caught Derived Exception";
   }
   catch(Base b) {
        cout<<"Caught Base Exception";
   }
   getchar();
   return 0;
}

In Java, catching a base class exception before derived is not allowed by the compiler itself. In C++, compiler might give warning about it, but compiles the code. 
For example, following Java code fails in compilation with error message “exception Derived has already been caught” 
 

Java




//filename Main.java
class Base extends Exception {}
class Derived extends Base  {}
public class Main {
  public static void main(String args[]) {
    try {
       throw new Derived();
    }
    catch(Base b) {}
    catch(Derived d) {}
  }
}

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :