On Tuesday, 26 February 2013 at 18:48:08 UTC, Jonathan M Davis wrote:
On Tuesday, February 26, 2013 09:02:11 Steven Schveighoffer wrote:
On one hand, I think the correct behavior is to return null, and let the program deal with checking the error, or use get if they have a default. If we throw an exception, people will end up catching the exception in order to avoid an unintended error. Exceptions are not good for flow control, they are for exceptional situations that you didn't plan for.

I think that it's far more correct to say that exceptions are for situations where it's reasonable for code to assume that something's the case when it might not be or when it's impossible for it to check. For instance, it's much cleaner to write a parser if the parser in general assumes that operations will succeed and throws when they don't. Then only a small part of the parser needs to worry about handling error cases. Or an example of when it would be impossible to check would be with file operations. You can (and should) check beforehand that the file exists, but there's no way to guarantee that the file will still exist when you actually operate on it (e.g. another process could delete it out from under you), so the file functions have to throw when the file
isn't there anymore or you don't have permissions or whatever.


That is best explanation I've read on the subject. I'm dead serious.

If you have to keep checking return values for functions, then you should probably be using exceptions. The place to avoid exceptions is when the odds of an operation succeeding are low (or at least that there's a fairly good chance that it'll fail), because then it really is just becoming flow control. But I actually think that pushing for exceptions to be for "exceptional situations" is harmful, as that leads to people not using them, and the code ends up checking return values when it would be much cleaner if it didn't have to. Of course, there are plenty of people who are quite poor at that balance and end up over-using exceptions as well, so striking a good balance can be
hard.


I want to add a point that you don't address here : it is easy to forgot to check return value. For instance, how much C code don't check the return value of printf ? I'd be surprised if it is even 1% . When you don't, and things fail, you program is in undefined state and start doing crap. As exception are costly only when the are thrown, it don't make any sense to not use them for speed, as doing crap very fast is rarely a goal that people want to achieve.

Reply via email to