Maggi Iggam
Maggi Iggam

Reputation: 692

How to print something when runtime error occurs somewhere in my C++ code?

What normally happens is when code faces Runtime error , it simply terminates with runtime flag , what i intend to do is print a custom message before termination & i wish to 'return 0' ,ie terminate code normally after printing custom message as if runtime never happened .

Any idea how to do it?

Upvotes: 2

Views: 10019

Answers (2)

cdonat
cdonat

Reputation: 2822

There are different reasons, why a programm might terminate.

First: An uncaught Exception was thrown. If that is, what you are looking for, then follow the advice, Paul Evans has given. With C++11, you might want to call get_terminate(), and call the returned teminate handler at the end of your new teminate handler:

terminate_handler old_terminate_handler = nullptr;

void new_terminate_handler() {
    std::cerr << "terminate due to error" << std::endl;
    if( old_terminate_handler != nullptr ) {
        old_terminate_handler();
    } else {
        std::abort();
    }
}

int main(int, char**) {
    old_terminate_handler = get_terminate();
    set_terminate(new_terminate_handler);
}

Second: a signal was received, that would normaly terminate the program. Install a signal handler to catch it:

void sig_handler(int signal) {
    new_terminate_handler();
}

// ...
std::signal(SIGTERM, sig_handler);
std::signal(SIGSEGV, sig_handler);
std::signal(SIGINT, sig_handler);
// ...

Third: The operating system might simply decide to kill the process. That is either done by a normal signal signal (e.g. SIGTERM), or by a signal, that can not be handled (e.g. SIGKILL) In the second case, you have no chance to notice that inside the programm. The first case is already covered.

Upvotes: 5

Paul Evans
Paul Evans

Reputation: 27577

First define your custom terminate handler, something like:

void f() {
    std::cout << \\ your custom message
}

then you want to call:

std::terminate_handler set_terminate( std::terminate_handler f );

to set up your function f as the terminate handler.

Upvotes: 3

Related Questions