Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program doesn't stop after exception

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 to stop the program after exception?

This is the code I am using:

try{
        if(BLER==-1) throw 12;
    }catch(int exception){
        cout << "ERROR: BLER value is invalid for x= " << x << ", BLER_input= " << BLER_input << ", m= "<< m << endl;
    }
like image 473
Shahab Avatar asked Mar 20 '23 14:03

Shahab


2 Answers

Some solutions:

  1. use return from your function (and do that accordingly to your return value) if you're doing this in the main() routine

  2. use exit(n) where n is the exit code (http://www.cplusplus.com/reference/cstdlib/exit/)

  3. abort() if that's a critical issue (http://www.cplusplus.com/reference/cstdlib/abort/)

Notice: as noted by James Kanze, exit and abort will NOT call the destructors of your local objects. This is worth noticing since you're dealing with classes.

like image 101
Marco A. Avatar answered Mar 23 '23 04:03

Marco A.


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

#include <iostream>
#include <cstdlib>

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 <stdexcept>

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.

like image 23
DevSolar Avatar answered Mar 23 '23 03:03

DevSolar