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;
}
Some solutions:
use return
from your function (and do that accordingly to your return value) if you're doing this in the main() routine
use 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
and abort
will NOT call the destructors of your local objects. This is worth noticing since you're dealing with classes.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With