Search code examples
c++virtualthrow

About an exception's virtual function in C++


In the following code:

#include <iostream>
class Exception{
public:
    virtual void print(){
        std::cerr << "Exception\n";
    }
};
class NullPointerException : public Exception{
public:
    void print(){
        std::cerr << "NullPointerException\n";
    }
};
int main(){
    try{
        throw NullPointerException();
    }catch(Exception e){
        e.print();
    }
    return 0;
}

Why the program compiled by G++ prints "Exception" instead of "NullPointerException". What should I do if I want "NullPointerException"?


Solution

  • You should always catch by reference. Const reference wouldn't be a bad idea either, since you normally don't need to modify an exception:

    catch(const Exception& e)
    

    Otherwise you are "slicing" the exception, which is a common mistake. Not to mention that copying an exception while it is in flight is a very bad idea--what if it needs to allocate memory to copy, and the reason it was thrown is because the system is low on memory?

    As an aside, you should probably derive your exceptions from std::exception.