C ++ exception catching

So, my C ++ program just crashed, and I got an error:

terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_S_create
Aborted

Now, what I recently added to my code is the SIGSEGV handler, so if it was a segmentation error, it would continue to print the stack trace.

How can I make an output handler for non-displayable (or more similar fuzzy) exceptions in C ++?

+3
source share
4 answers

Use the set_terminate function, which sets the completion handler function:

, - . , , .

+5

@vitaut, ++ 11, , std::set_terminate.

, , std::terminate , , std::current_exception , , .

++ 11 N3242, 15.3.7 ():

, ( ) catch . [: . - end note] , , std:: terminate() std:: () - . , catch std:: () - .


Andrzej ++, , :

[[noreturn]] void onTerminate() noexcept
{
    if( auto exc = std::current_exception() ) { 
        // we have an exception
        try{
            rethrow_exception( exc ); // throw to recognize the type
        }
        catch( MyException const& exc ) {
            // additional action
        }
        catch( MyOtherException const& exc ) {
            // additional action
        }
        catch( std::exception const& exc ) {
            // additional action
        }
        catch( ... ) {
            // additional action
        }
    }

    std::_Exit( EXIT_FAILURE );
}
+1

try - catch(...) . - :

try {
   doStuff();
} catch( std::exception& e ) {
  //handle std::exception-derived exceptions
} catch(...) {
  //handle all other exceptions
}     
0

set_terminate.

You can catch all C ++ exceptions with the catch-all clause catch (...) {}.

0
source

Source: https://habr.com/ru/post/1776209/


All Articles