What are the differences between Errors and Exceptions?
Error
When an operation fails, does not succeed.
Exception
When an alternative or exceptional route appears.
Example
If a delivery guy tries to deliver my package but he failed to do so, that's an Error.
But if he got attacked by my dog, that's an Exception.
If the he got attacked by my dog, I throw an Exception that my dog attacked him.
If the package has not been delivered, you don't throw an Exception. You return false or return an error message "Package could not be delivered".
try {
DeliverPackage();
}
catch (Exception $e) {
return "Could not deliver the package because my dog attacked him";
}
return false;
Thats all folks~
Top comments (1)
Nice article.
I would like to quote my Java teacher here: exception are for exceptionnal cases. You want to use them when the piece of code you're writing cannot make a decision based on the current situation. Then you throw an exception to delegate that decision to the calling class and so on...
If the code can handle the situation at hand, for instance by returning a value indicating the error, then it should not throw an exception.
Here's an example: