Introduction
This blog will discuss the concept of exceptions and member functions. First, we will discuss how to catch base and derived classes as exceptions. After that, we will discuss the member function. To catch an exception for both base and derive class then we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached..
Exceptions Handling
Here we will see how we can catch base and derived classes as exceptions. If we want to catch exceptions for both base and derived classes, we will have to put the catch block of the base class after the derived class.
Now let us discuss this concept with the help of a suitable example. Here in this example, we have placed the catch block of the derived class before the base class,
Code in C++
#include <bits/stdc++.h>
using namespace std;
class baseClass
{
};
// class derivedClass inherit the class baseClass
class derivedClass : public baseClass
{
};
int main()
{
derivedClass derived;
try
{
throw derived;
}
catch (derivedClass derived)
{
cout << "Derived Exception"; // catch block of the derived class
}
catch (baseClass base)
{
cout << "Base Exception"; // catch block of the base class
}
return 0;
}
Output:
Derived Exception
Now, we will discuss another example here, we will place the catch block of the derived class after the catch block of the base class.
Code in C++
#include <bits/stdc++.h>
using namespace std;
class baseClass
{
};
// class derivedClass inherit the class baseClass
class derivedClass : public baseClass
{
};
int main()
{
derivedClass derived;
try
{
throw derived;
}
catch (baseClass base)
{
cout << "Base Exception"; // catch block of the base class
}
catch (derivedClass derived)
{
cout << "Derived Exception"; // catch block of the derived class
}
return 0;
}
Output:
warning: exception of type 'derivedClass' will be caught
Base Exception
Try and compile with online c++ compiler.
Here as you can see in the output, there is a warning, and hence we cannot reach the catch block of the derived class. Therefore, we need to place the catch block of the derived class before the catch block of the base class.