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;
}
The
catch
handler in C++ allows one to handle the error outside the normal execution path for the code. Once handled, C++ assumes it is safe to resume normal operation or the program.If this is not the case, say you just want to log the error, you are free to re
throw
the exception which causes to error to propagate further up the stack.If the exception does not get caught at all, the C++ function
std::terminate
will get called. The default behavior is to callabort
.Is probably the best thing to do you your case is just rethrow the exeception by calling
throw
at the end of the catch block.try using the return command like this
Some solutions:
use
return
from your function (and do that accordingly to your return value) if you're doing this in the main() routineuse
exit(n)
where n is the exit code (http://www.cplusplus.com/reference/cstdlib/exit/)abort()
if that's a critical issue (http://www.cplusplus.com/reference/cstdlib/abort/)Notice: as noted by James Kanze,
exit
andabort
will NOT call the destructors of your local objects. This is worth noticing since you're dealing with classes.To stop execution of a program after catching an exception, just call
std::exit()
in thecatch
block:Live demo here.
This works outside of
main
as well. You can substituteEXIT_FAILURE
with anyint
value you want, portably in the0-255
range.If you can / must handle the problem in the current function, you can (and should) terminate right there:
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...
...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
.Use the function exit:
exit(1);
, where 1 is the exit code (normally non-zero signals an error). You can use alsoabort()
if you consider the exception as critical error.