Program doesn't stop after exception

后端 未结 6 938
悲哀的现实
悲哀的现实 2021-01-21 03:11

I am using eclipse in Ubuntu 12.04. I use some exceptions in my program and when they are caught it gives me cout correctly. But the program continues to the end. Is there a way

6条回答
  •  没有蜡笔的小新
    2021-01-21 04:01

    If you can / must handle the problem in the current function, you can (and should) terminate right there:

    #include 
    #include 
    
    if ( BLER == -1 )
    {
        std::cout << "BLER value is invalid." << std::endl;
        std::exit( EXIT_FAILURE );
    }
    

    Exceptions are meant to be thrown when you have an error condition, but no idea how to handle it properly. In this case you throw an exception instead of an integer, optionally giving an indication of the problem encountered in its constructor...

    #include 
    
    if ( BLER == -1 )
    {
        throw std::runtime_exception( "BLER value is invalid" );
    }
    

    ...and catch that somewhere up the call tree, where you can give a yet better error message, can handle the problem, re-throw, or terminate at your option). An exception only terminates the program by default if it is not caught at all ("unhandled exception"); that's the whole idea of the construct.

    Throwing an integer and catching it in the same function is (ab-)using exceptions as in-function goto.

提交回复
热议问题