Sign in to follow this  
CDProp

When to use exception handling? (C++)

Recommended Posts

Hello. I'm currently brushing up on exception handling. Most of the examples I'm reading, though they may be purposely trivial, seem like they could be more-easily handled by simply checking the return value of the function you call (assuming it returns success, otherwise some error code) and then going from there. So, I'm not quite sure.

Share this post


Link to post
Share on other sites
Exceptions are superior to manual error code techniques in cases where the exception should never occur in normal execution (i.e. if the error is exceptional behaviour). This allows you to avoid cluttering up the calling code with error checking logic and just assume that everything will always go as planned.

In the exceptional cases where an error does occur, the throwing/catching/unwinding process does incur a significant performance penalty (i.e. worse performance than manual error handling), but this is mitigated by the fact that in all of the non-exceptional cases you didn't pay the performance cost of the error-handling logic.

If a particular error will be a common occurrence (i.e. not exceptional behaviour), then just use traditional error handling techniques instead. The exception to this guideline is inside a constructor - the preferred error-handling mechanism for when a constructor fails is to throw an exception.

Share this post


Link to post
Share on other sites
Yes , but the *calling code* doesn't need to bother checking if an error occurred or not (e.g. by looking at return-codes, etc...). It can assume that everything is ok and continue executing, because the exception will basically goto your program back up to the correct catch statement in the case of an error.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this