简体   繁体   中英

C++ Custom exception derived from std::exception not being caught

I´m writing a custom exception class with the following code:

#include <iostream>
#include <string>
#include <memory>
#include <sstream>
#include <iomanip>
#include <algorithm>    


class MyException : public std::exception {

public:
    MyException();
    explicit MyException(std::string message);
    MyException(std::string source, std::string message);
    MyException(int code, std::string source, std::string message);
    const char *what() const throw();


private:
    int exceptionCode;
    std::string exceptionSource;
    std::string exceptionMessage;
};


MyException::MyException() :
        exceptionCode(0),
        exceptionSource ("No source."),
        exceptionMessage ("No message.") {}

MyException::MyException(std::string message) :
        exceptionCode(0),
        exceptionSource ("No source."),
        exceptionMessage (std::move(message)) {}

MyException::MyException(std::string source, std::string message) :
        exceptionCode(0),
        exceptionSource (std::move(source)),
        exceptionMessage (std::move(message)) {}

MyException::MyException(int code, std::string source, std::string message) :
        exceptionCode(code),
        exceptionSource (source),
        exceptionMessage (message) {}

const char *MyException::what() const throw()
{
    std::cout << "What:" << exceptionMessage << std::endl;

    std::stringstream s;
    s << "MyException Data:" << std::endl;
    s << "Code    : " << exceptionCode << std::endl;
    s << "Source  : " << exceptionSource << std::endl;
    s << "Message : " << exceptionMessage << std::endl;

    std::string whatString = s.str();
    return whatString.c_str();
}


void test()
{
    throw new MyException("test", "This is a test");
}


int main()
{
    try
    {
        test();
    }
    catch (const std::exception &exc)
    {
        std::cerr << "Exception detected:" << std::endl;
        std::cerr << exc.what();
        throw exc;
    }
    catch (...)
    {
        std::cerr << "An unknown exception was called." << std::endl;
        throw;
    }
}

It compiles fine, but I cannot catch my own exception from the catch (const std::exception &exc) block. It is only caught by the catch (...) block.

As MyException is inherited from std::exception I supposed it was gonna be caught by the first catch block... Why is that not happening ?

Original code link here

Throw by value:

void test()
{
    throw MyException("test", "This is a test");
}

Technically, you could catch the new 'ed exception by pointer, but
do not do it :

catch (const std::exception* exc) // bad practice

For more details, see What should I throw/catch?

or

Alexandrescu/Sutter's, C++ Coding Standards: 101 Rules... , rule 73:

Throw by value, catch by reference

This does not directly answer the question, but it's really important

this function is an unsafe crash waiting to happen:

const char *MyException::what() const throw()
{
    std::cout << "What:" << exceptionMessage << std::endl;

    std::stringstream s;
    s << "MyException Data:" << std::endl;
    s << "Code    : " << exceptionCode << std::endl;
    s << "Source  : " << exceptionSource << std::endl;
    s << "Message : " << exceptionMessage << std::endl;

    std::string whatString = s.str();
    return whatString.c_str();
}

string::c_str() is returning the c-string inside the temporary string called whatString .

When you write an exception class like this, you must store the complete error message in the exception - build it in the constructor.

here's a safe replacement:

class MyException : public std::exception {

public:
    MyException();
    explicit MyException(const std::string& message);
    MyException(const std::string& source, const std::string& message);
    MyException(int code, const std::string& source, const std::string& message);
    const char *what() const throw();

private:
    // helper function
    static std::string make_message(int code, const std::string& source, const std::string& message);
    std::string message;
};


MyException::MyException() :
MyException(0, "No source.", "No message.") {}

MyException::MyException(const std::string& message) :
MyException(0, "No source.", std::move(message)) {}

MyException::MyException(const std::string& source, const std::string& message) :
MyException(0, std::move(source), std::move(message)) {}

MyException::MyException(int code, const std::string& source, const std::string& message) :
message(make_message(code, source, message))
{}

const char *MyException::what() const throw()
{
    // message is a class member, not a temporary
    return message.c_str();
}

std::string MyException::make_message(int code, const std::string& source, const std::string& message)
{
    std::stringstream s;
    s << "MyException Data:" << std::endl;
    s << "Code    : " << code << std::endl;
    s << "Source  : " << source << std::endl;
    s << "Message : " << message << std::endl;

    // takes a copy, returns a copy - safe!
    return s.str();
}

Also, when you re-throw, don't do this:

catch (const std::exception &exc)
{
    std::cerr << "Exception detected:" << std::endl;
    std::cerr << exc.what();
    throw exc; // <--- this is bad - you're potentially slicing!
}

do this instead:

catch (const std::exception &exc)
{
    std::cerr << "Exception detected:" << std::endl;
    std::cerr << exc.what();
    throw;     // <--- ok, compiler will now rethrow the complete object
}

This:

throw new MyException("test", "This is a test");

Should be:

throw MyException("test", "This is a test");

Otherwise you'd need to catch by pointer, which isn't standard practice. Your current catch by const-reference is idiomatic and correct--you just need to throw the exception directly rather than dynamically allocating.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM