Error handling in php, die vs exceptions

For example, my use would be:

$check = 'no'; if($check == 'yes') { //do stuff } else { die('Error found'); } 

Many developers that I have seen use:

 if($check == 'yes') { //do stuff } else { throw new Exception('Error found.'); } 
  • Which method is better?
  • Any advantage of throwing an exception instead of stopping script execution?
+4
source share
4 answers

I would like to save all the problems and pass this stack to you here: PHP Error Handling: die () Vs trigger_error () Vs throw Exception A very detailed explanation of their use, I think that can not be said better.

+7
source

Which method is "better"?

It depends on your needs. This is not to say which one is better (and there are other ways to handle errors, and you should also consider when you really want to discuss error handling, for which this site is probably not suitable).

Any advantage of throwing an exception instead of stopping script execution?

An exception can be caught, but die cannot be caught. If you want to test your code, for example, die are often a show stopper.

In addition, an exception may contain more information and carry it more accurately. A message, for example, is more accessible with an exception than with die . The exception stores the file and the line in which it was selected. For debugging, there is a stack trace, etc.

0
source

Exceptions are better (in the design of large sites), because:

  • They do not stop the script immediately (you have the opportunity to inform the user on page 5xx about the internal server error)
  • If you decide to handle the error differently in the future, you can do it without changing the source code.
  • Exceptions provide backtracking and ease debugging
  • I'm not sure, but destructors should not be called when die is used (exceptions provide the ability to execute them).
  • You can create many types of exceptions, each for a different error, and handle them easily later.

You should use die , probably only in small scripts and pages where you do not need to create style errors for use or in case of a fatal error (cannot include the main library in the index or something like that).

0
source

You can use both throw new Exception parameters if some exception occurs (database connection or query, page or file not found ...), and then catch where appropriate. Then, perhaps a log error in the file, send an email to the administrator, and then use die("Some textual message to user."); . If you do not want to use die (), you can show the user about 404 not found or 500 internal error pages.

0
source

Source: https://habr.com/ru/post/1393394/


All Articles