Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch derived exception when returning reference of base class type?

I'm writing a windows application in C++ and encountered the following problem when working with exceptions.

I have a base exception class from which all other exceptions derive from. In the base class I have a method for the error message of any exception. That method then returns the exception (through '*this').

Now, the problem occurs when I want to extend a derived exception and later user it in a catch block. Since the extend method is declared in the base class, the catch block catches the base class instead of the derived class. Is there any way of working around this so that the correct derived class is caught instead?

Here are some code illustrating the problem:


// DECLARATIONS

class BaseException {
    BaseException() { }

    Exception& extend( string message ) {
        // extend message

        return *this;
    }
}

class DerivedException : public BaseException {
    DerivedException() : Exception() { }
}



// RUNNING CODE

int main() {
    try {
         ...

         try {
             ...

             // Something goes wrong
             throw DerivedException( "message1" );
         }
         catch ( DerivedException& exc ) {
             throw exc.extend( "message2" );
         }
    }
    catch ( DerivedException& ) {
        // Here is where I *want* to land
    }
    }
    catch ( BaseException& ) {
        // Here is where I *do* land
    }
}

At the moment I have "solved" it by not making the extend method virtual, but declaring it in each exception with correct return type. It works, but it's not pretty.

like image 685
gablin Avatar asked Apr 08 '26 12:04

gablin


1 Answers

It would be much simpler to separate the extend() call and the re-throwing of the exception:

 catch ( DerivedException& exc ) {
     exc.extend( "message2" );
     throw;
 }

This way extend() doesn't have to return anything and always the right exceptions are thrown/caught.

like image 180
sth Avatar answered Apr 15 '26 02:04

sth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!