8

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 ?
ZeroSuf3r
  • 1,961
  • 8
  • 25
  • 36

3 Answers3

1

You can use both, throw new Exception if some exceptional situation occurs (database connection or query, page or file not found...), and then catch it where that suits you. Then maybe log error to file, send mail to administrator and then use die("Some textual message to user.");. If you don't want to use die() you can show user some 404 not found or 500 internal error page.

fsasvari
  • 1,891
  • 19
  • 27
1

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
0

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

  • They don't stop script immediately (you've got a chance to inform user in nice 5xx page about internal server error)
  • If you decide to handle error differently in the future you can do so without modifying original code
  • Exceptions provide backtrace and ease up debugging
  • I'm not sure, but destructors shouldn't be called when die is used (exceptions provide option to execute them)
  • You may create lot of Exceptions types, each for different kind of error and handle them easily later

You should use die probably only in smaller scripts and pages where you don't need to style error for use or in case of fatal error (cannot include main library into index or something like that).

Vyktor
  • 20,559
  • 6
  • 64
  • 96