Difference between exceptions and errors?

What is the difference between error and exception?

I have read numerous resources on the Internet and in several books, but the explanations provided are not very thorough. Therefore, I am still confused.

Thanks!

Edit: Looks like I asked two questions that were probably confused. The main question I wanted to answer is the difference between errors and exceptions . So, I edited above to be more specific. Thank you all for your answers.

+4
source share
3 answers

There is no need to "do" or the "best" way to handle errors.

Generally speaking, there are two types of errors

  • Those that are processed by other parts of the program. The user never sees or does not know about these errors, at least not in a direct form.
  • Those that caused a sufficient failure that the user should be informed as such.

Note that none of them has anything to do with the specific PHP mechanisms that you will use to handle errors.

If you use exceptions ... Then I recommend using exceptions in all directions. Register an exception handler and let it do most of the work — including other PHP errors . Invalid login information?

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

Then you have a bunch of options to implement.

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

Or, if you decide so, let the exception handler do it. Perhaps in an even 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 are not the only way, and some are not even considered a good way .

+5
source

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

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

+6
source

On the one hand, exceptions may continue to execute the script. In addition, trigger_error always reports the line and file called by trigger_error.

0
source

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


All Articles