Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default unhandled exception behaviour

I have this code:

#include <iostream>
#include <exception>

class TestException : public std::exception
{
public:
    char const* what() const throw() override { return msg_.c_str(); }

protected:
    std::string & message() throw() { return msg_; }

private:
    std::string msg_;
};

void ThrowIt()
{
    throw TestException();
}

int main()
{
    ThrowIt();
}

Running this when built in either Release or Debug on Windows compiled with Visual Studio results in program termination, same goes for when compiled with GCC on a Linux machine, the result is :

terminate called after throwing an instance of 'TestException'
what(): Aborted

Both terminate the program once an unhandled exception is caught. Is this behaviour strictly system specific or is this specified by the standard? Is there a cross-platform way that I can reroute every exception not handled by catch to a handler instead of just terminating the program?

like image 873
Hatted Rooster Avatar asked Aug 23 '26 02:08

Hatted Rooster


1 Answers

I'm not sure what standard guarantees but in practice with GCC, clang and MSVC you may use std::current_exception() inside terminate handler to handle the exception. Like this:

#include <stdexcept>
#include <iostream>

void f()
{
    try
    {
        std::rethrow_exception(std::current_exception());
    }
    catch(const std::exception &e)
    {
        
        std::clog << "exception: " << e.what() << std::endl;
    }
}

int main()
{
    std::set_terminate(f);
    throw std::runtime_error("oh no");
    return 0;
}
like image 69
peper0 Avatar answered Aug 25 '26 17:08

peper0



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!