when to use exceptions and when to return values indicating success/failure?

Feb 14, 2011 at 2:43pm
One of the books I have read states that exceptions are thrown only in the event of serious errors and not so serious errors can be handled by returning values like a bool or an int indicating whether the operation was performed successfully or not, but what constitutes a serious error and a not so serious error?
Last edited on Feb 14, 2011 at 2:43pm
Feb 14, 2011 at 3:05pm
Exceptions should be thrown in any of the following cases:

1. An exceptional thing occurred. Something that is not a normal working scenario (normal working scenarios can include error cases. For example, prompting the user to enter a filename from which you'll read data. If they enter a filename that does not exist, that is not exceptional. Reading the file once, closing it, then failing to open it a second time for reading is exceptional -- the file should have been there the second time too.)

2. It is impossible to return an error code. Constructors cannot return values, and many operators cannot either. You have no choice but to throw when any error occurs within them.

3. The error is not likely to be handled by the immediate caller of the function. The idea here is that you don't want to absolutely litter your code with try-catch blocks. Generally exceptions are handled in very few places within an application. Reason: first, try-catches aren't quite free -- the compiler must generate hidden code to deal with them. Secondly, the syntax for catching is much uglier than just checking a return code from a function.
Feb 14, 2011 at 3:05pm
Exceptions should be thrown in any of the following cases:

1. An exceptional thing occurred. Something that is not a normal working scenario (normal working scenarios can include error cases. For example, prompting the user to enter a filename from which you'll read data. If they enter a filename that does not exist, that is not exceptional. Reading the file once, closing it, then failing to open it a second time for reading is exceptional -- the file should have been there the second time too.)

2. It is impossible to return an error code. Constructors cannot return values, and many operators cannot either. You have no choice but to throw when any error occurs within them.

3. The error is not likely to be handled by the immediate caller of the function. The idea here is that you don't want to absolutely litter your code with try-catch blocks. Generally exceptions are handled in very few places within an application. Reason: first, try-catches aren't quite free -- the compiler must generate hidden code to deal with them. Secondly, the syntax for catching is much uglier than just checking a return code from a function.
Topic archived. No new replies allowed.