Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php OOP Exceptions or die()?

I am developing some project. And I want to control different errors. I know that in all popular frameworks and php projects there are different Exceptions. But I think that is not required work. If the error is occured we can make die() with our message. 1. What are the main pluses of Exceptions? 2. Can I control my errors with die()?

Thank you.

like image 669
Alex Pliutau Avatar asked Feb 26 '26 19:02

Alex Pliutau


1 Answers

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...

like image 146
ircmaxell Avatar answered Mar 01 '26 09:03

ircmaxell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!