Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C++ | Exception Handling | Question 4

  • Difficulty Level : Easy
  • Last Updated : 28 Jun, 2021

Output of following program

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.




#include<iostream>
using namespace std;
  
class Base {};
class Derived: public Base {};
int main()
{
   Derived d;
   try {
       throw d;
   }
   catch(Base b) {
        cout<<"Caught Base Exception";
   }
   catch(Derived d) {
        cout<<"Caught Derived Exception";
   }
   return 0;
}

(A) Caught Derived Exception
(B) Caught Base Exception
(C) Compiler Error


Answer: (B)

Explanation: 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.

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.


Quiz of this Question

My Personal Notes arrow_drop_up
Recommended Articles
Page :