set_terminate()

hi there,
just testing set_teminate() but i dont see what's wrong here.. i would expect the message to be displayed but the program just crashes without showing anything... maybe something system-dependent? (i'm using codeblocks).. thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include <iostream>
#include <exception>

void adios()
{
    std::cerr << "leaving this program. bibi... " << std::endl;
    std::abort(); // <-tried to comment this out, but no difference
}
int main()
{

    int a=6,i=0;
    std::set_terminate(adios);
    std::cout << a/i << std::endl;

    return 0;
}
In line 15 you're dividing by 0 which is an undefined, I think that might be part of your problem.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <exception>
#include <cstdlib>
#include <vector>

void adios()
{
    std::cerr << "leaving this program. bibi... " << std::endl;
    // std::abort(); // #include <cstdlib> (default)
}

int main()
{
    std::set_terminate(adios);

    int i ;
    std::cout << "enter 0 to call terminate, 1 for unhandled exception: " ;
    std::cin >> i ;

    if( i == 0 ) std::terminate() ;
    else if( i == 1 ) { std::vector<int>().at(22) ; }
}
thanks, i see it's displaying the msg now before crashing...
one thing though, i thought terminate() would be invoked automatically in case of any unhandled exception; i didnt think terminate() had to be explicitly triggered...is this becasue we provide set_terminate() with an argument?
> i thought terminate() would be invoked automatically in case of any unhandled exception;

Yes.

Also in certain other unrecoverable error situations.
http://en.cppreference.com/w/cpp/error/terminate


> i didnt think terminate() had to be explicitly triggered...
> is this becasue we provide set_terminate() with an argument?

No, it does not have to be explicitly triggered by us. Even if we did not have line 20, std::terminate() would still be called in case of unhandled exceptions.

However, it is a function; we can directly call it from within our code to terminate the program if we want.

thank you
Topic archived. No new replies allowed.