Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between exceptions and errors?

What is the difference between an error and an exception?

I have read numerous resources online and in a couple of books, but the explanations provided are not very thorough. As such, I am still confused.

Thanks!

Edit: It looks like I asked two questions which was probably confusing. The main question that I wanted an answer to is the difference between errors and exceptions. So, I have edited the above to be more specific. Thanks everybody for your answers.

like image 332
Mike Moore Avatar asked May 27 '10 17:05

Mike Moore


2 Answers

There is no "should" or "best" way to do error handling.

Generally speaking, there are two types of errors

  1. Those which are handled by other parts of the program. The user never sees or knows about these errors, at least not in a direct manner.
  2. Those which have caused enough failure that the user needs to be informed as such.

Notice that neither of these have anything to do with the specific PHP mechanisms you'd use to handle errors.

If you use exceptions... Then I recommend using exceptions across the board. Register an exception handler and let it do most of the work - including other PHP errors. Invalid login details?

class InvalidLoginException extends Exception
{
  protected $message = 'Login information is incorrect. Please try again.';
}

Then you have a bunch of choices for implementation.

try {
  $user->login(); // will throw and InvalidLoginException if invalid
}
catch ( InvalidLoginException $e )
{
  // display an error message
}

Or, if you so choose, let the exception handler do it. Maybe even in a more flexible way

class ApplicationErrorException extends Exception{}
class InvalidLoginException extends ApplicationErrorException 
{
  protected $message = 'Login information is incorrect. Please try again.';
}

Then, in the exception handler

if ( $exception instanceof ApplicationErrorException )
{
  // dislpay error message
}

But exceptions aren't the only way, and by some not even considered a good way.

like image 132
Peter Bailey Avatar answered Oct 03 '22 09:10

Peter Bailey


Neither. Exceptions and Errors are for when the code does something wrong. The user is more or less expected to enter incorrect login information. Check if the username/password are correct, if not, redirect the user back to the login page (header('location:login.php?failed=1');) and then if $_GET['failed'] is set, display a message. That'd be the easiest way.

With regard to exceptions/errors... you should generally stick to exceptions. You throw an exception, and then you catch it and deal with it. I think trigger_error is more for propagating the error back to the client when you don't know how to handle the error in a catch block.

like image 22
mpen Avatar answered Oct 03 '22 09:10

mpen