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.
There is no "should" or "best" way to do error handling.
Generally speaking, there are two types of errors
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With