Well, you could use die()
. But that makes all errors fatal. Meaning that you cannot try to recover from the error at all. In some cases that's fine to do.
But in most cases, you may want the ability to "clean up" after the error, or to try another method. This is where exceptions come in handy... They let you chose where and if you want to handle the error. They let you try to gracefully recover from the errors.
For example, let's say you have a method which downloads a file from a remote server: downloadFromRemoteServer($address);
If you use die()
, if the download fails, the script terminates. End of story.
But if you use exceptions, you could try another server or even try a different method (HTTP vs FTP, etc):
try {
$file = downloadFromRemoteServer('http://example.com/foo');
} catch (DownloadFailedException $e) {
try {
$file = downloadFromRemoteServer('http://secondtry.example.com/foo');
} catch (DownloadFailedException $e2) {
die('Could not download file');
}
}
return $file;
But remember that Exceptions are useful only for exceptional circumstances. They are not meant to be used for any possible error. For example, if a user doesn't verify their email address correctly, that's not exceptional. But if you can't connect to the database server, or have a conflict in the DB, that would be an exception circumstance...