Please see the expected flow of below code
In this case base class exception is catching as this expected behavior due to its polymorphic nature.
#include <stdio.h>
#include<iostream.h>
using namespace std;
void main() {
try {
//throw CustomException();
throw bad_alloc();
}
///due to poly morphism base class reference will
catch(exception &ex) {
cout<<"Base :"<<ex.what()<<endl;
}
catch(bad_alloc &ex) {
cout<<"Derieved :"<<ex.what()<<endl;
}
}
output
bad_alloc
But if I am making a custom exception like shown in the below code, the derived class is catching the exception, even if the base class catch is appearing first in the catch
blocks:
class CustomException : exception {
public :
CustomException() { }
const char * what() const throw() {
// throw new exception();
return "Derived Class Exception !";
}
};
void main() {
try {
throw CustomException();
//throw bad_alloc();
}
///due to poly morphism base class reffrence will
catch(exception &ex) {
cout<<"Base :"<<ex.what()<<endl;
}
catch(CustomException &ex) {
cout<<"Derived :"<<ex.what()<<endl;
}
}
expected output :
Base : Derived Class Exception !
Actual output:
Derived: Derived Class Exception !
The default inheritance access specifier for classes declared using the class
keyword is private
. This means that CustomException
inherits from exception
private
ly. A derived class that uses private
inheritance can't be bound to a reference to its parent class.
If you inherit public
ly it will work fine:
class CustomException : public exception // <-- add public keyword here
{
public :
CustomException()
{
}
const char * what()
{
return "Derived Class Exception !";
}
};
int main()
{
try
{
throw CustomException();
}
catch(exception &ex)
{
cout<<"Base :"<<ex.what()<<endl;
}
catch(CustomException &ex)
{
cout<<"Derived :"<<ex.what()<<endl;
}
}
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With