Originally Posted by
swgh
Why don't you just do this?
It is simple and effective
It's also very bad, for exactly the reason I mentioned in the post before yours. exit() does not unwind the stack; it does not call destructors for objects. Any resource you allocated (which should be freed in some destructor somewhere) remains allocated. C++ file streams will not be flushed, resources you acquired from the OS will not be returned, cats and dogs will live together, etc.
Yes, it works in certain situations in certain kinds of code, but it's a very bad habit to get into.
This is included ONLY for backwards compatibility with C (it's a C function) -- and C didn't have destructors. In general it's one of those lines of code that simply shouldn't be used in C++.
If you want an equivalent in C++, do something like this:
Code:
class ExitException{
public:
ExitException(int c){ m_c = c;}
int GetCode(){ return m_c;}
private:
int m_c;
};
...
int main(){
try{
/* Body of your code goes here */
}
catch(ExitException e){
return e.GetCode();
}
}
....
/* Inside some function, and we want to exit on an unrecoverable error */
throw ExitException(1);
That does the same sort of thing but DOES unwind the stack, and all variables going out of scope have their destructors properly called.
You could simplify this by just throwing an int to begin with, although I prefer not throwing primitives. Under that case it would look like:
Code:
int main(){
try{
/* Body of your code goes here */
}
catch(int i){
return i;
}
}
....
/* Inside some function, and we want to exit on an unrecoverable error */
throw 1;