Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error handling in php, die vs exceptions

Tags:

exception

php

For example, my usage would be:

$check = 'no';

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

Many developer's what i seen use:

if($check == 'yes') {
      //do stuff
   } else {
      throw new Exception('Error found.');
   }
  1. Which one method is 'better' ?
  2. Any benefit's throwing an exception instead of stoping executing script ?
like image 266
ZeroSuf3r Avatar asked Jan 27 '12 16:01

ZeroSuf3r


People also ask

What is the difference between exception and error in PHP?

Summary of Differences: The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser. Exceptions are used to change the normal flow of a script if a specified error occurs. This can be done using PHP die() Function.

What is exception and error handling in PHP?

With PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

How is error handling done in PHP?

By default, PHP sends an error log to the server's logging system or a file, depending on how the error_log configuration is set in the php. ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.

Can we catch fatal error in PHP?

In PHP 7, fatal errors are now exceptions and we can handle them very easily. Fatal errors result in an error exception being thrown. You need to handle non-fatal errors with an error-handling function. Here is an example of catching a fatal error in PHP 7.1.


2 Answers

I would like to save everyone some trouble and refer you to this stack here: PHP Error handling: die() Vs trigger_error() Vs throw Exception Very detailed explanation of their uses, I believe it couldn't be said any better.

like image 128
HenryGuy Avatar answered Sep 28 '22 04:09

HenryGuy


Which one method is 'better' ?

This depends on your needs. It can't be said which one is better (and there are other ways of error handling as well you should put into consideration when you actually want to discuss error handling which this site is probably not the right place for).

Any benefit's throwing an exception instead of stoping executing script ?

An exception can be caught, a die can't be caught. If you want to test your code for example, dies are often a show-stopper.

Next to that an exception can carry more information and carry it more precisely. The message for example is more accessible with an exception than it is with a die. An exception keeps the file and line where it was thrown. For debugging there are stack traces and so on.

like image 25
hakre Avatar answered Sep 28 '22 04:09

hakre