reasonable error handling
reasonable error handling
hi,
i'm writing programs in c++ for a while and realized after some time of very bad coding that programs should report errors. since these programs are usually quite small (say below 500 lines) i was too lazy to learn the whole throw/catch mechanism but used instead something like this:
#define ERR_TOO_SMALL 1 #define ERR_TOO_LARGE 2 #define STATUS_OK 0 class MyClass { public: MyClass * do_something(int foo) { if(foo>10) { status = ERR_TOO_LARGE; return this; } //do something } int getStatus { return status; } private: int status } int main() { MyClass * a; if( a->do_something()->status != STATUS_OK) { //now check which error occured.. } }
Is this common style ? Are there better methods ?
robert1 Oct 05, 9:54AM
Hey,
Throw and Catch should really be used as a method of last resort, they shouldn't be used as part of the everyday program flow. Though I'm sure some might disagree.
So putting in sensible check to ensure the inputs are correct and within range as you've demonstrated is exactly right.
You should read up a little on the whole throw catch stuff. See something like C++ Gotchas by Stephan C.Dewhurst.. The whole system is extremely clever and was essentially introduced to help make C++ more stable, moving it towards Java and the like.
Quoting from this book:
[quote:02bd025c60]
.. when ever a throw is made, the system copies the exception object to a temporary in a 'safe' location.... This mean this temporary will be available until the last catch clause has been executed... .. It is an important property because, to put it bluntly, when you throw and exception all hell breaks loose. That temporary is the calm in the eye of the exception-handling maelstrom. [/quote:02bd025c60]
In other words, the over head of an throw and catch is high as the system unwinds the stack and gets everything back to where it needs to be... Hence why you should use them to catch every day occurrences. They're very often added at the end to catch anything else someone forgot to consider, or might arise once a month..
Will.
Login