Error codes on the other hand can be ignored.
PutLionInCage();
PokeLionWithStick();
I'd rather PutLionInCage() throws if there is a problem.
Error codes on the other hand can be ignored.
PutLionInCage();
PokeLionWithStick();
I'd rather PutLionInCage() throws if there is a problem.
If you rely solely on return codes to indicate an invalid state and the caller is free to ignore the error codes, it makes it much easier for the program to continue on doing invalid things - this is akin to wrapping everything with try/catch blocks and suppressing exceptions. Even more, when you do realize something is wrong, a system utilizing exceptions is generally much better at propagating information about the original problem.
There are good arguments in favour of exceptions, but I don't think this is one of them. If Java has taught us anything, it is that trying to force someone to handle exceptions just causes a lot of code that says:
catch (Exception e)
{
// silently ignore e
}// This should never happen.
(Until it does)
I have mixed feelings about checked exceptions. They seem like a great idea in theory - if there are known error states, then making them explicitly known and forcing the consumer to acknowledge them in some way seems reasonable. In practice, a lot of the time the only response to a checked exception is "let it propagate up - there isn't anything useful I can do", which leads to extra code and can be annoying.
Even though I don't have quite the negative feelings toward them others do, if I were involved in designing a new language today, I'd probably vote against including them. It would possibly be nice if a method could explicitly declare which exceptions it was likely to throw, and then an IDE or static analysis tool could use those to aid consumers of the API, without forcing them to deal with every single one.
Interestingly enough, I view Scala's Option construct as being somewhat similar - forcing the consumer to acknowledge that a particular call could return a null value - but it doesn't seem to provoke the same negative visceral reactions that checked exceptions do.
Furthermore if the dev just wraps the entire process in that silent catch then the lion doesn't get poked!
If you write a library are you thinking that everyone is going to use it properly?
My point is that exceptions help people to learn how to use APIs (its kinda like documentation that appears through use!) and exceptions make things _safer_.
I appreciate you could write the above in two try catches but my point is that it would look more wrong. The code above _looks_ fine and that's my point.
I totally agree that exceptions are far superior than checking return values.