Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base class catch not catching exception even if it is appearing before derived class catch

Tags:

c++

exception

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 !
like image 493
Mohit Avatar asked Dec 23 '22 02:12

Mohit


1 Answers

The default inheritance access specifier for classes declared using the class keyword is private. This means that CustomException inherits from exception privately. A derived class that uses private inheritance can't be bound to a reference to its parent class.

If you inherit publicly 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

like image 103
Miles Budnek Avatar answered Jan 23 '23 09:01

Miles Budnek