In the Java programming language, there is a relatively perfect exception handling mechanism, and the internal package is better. The exception handling mechanism in PHP is not so powerful and perfect, how is it implemented, is it to treat each exception as an error?
Reply content:
In the Java programming language, there is a relatively perfect exception handling mechanism, and the internal package is better. The exception handling mechanism in PHP is not so powerful and perfect, how is it implemented, is it to treat each exception as an error?
PHP has built-in a base class Exception, you need to inherit this class to define your own exceptions.
When an exception is triggered, it is caught by the catch keyword, and the exception is handled.
catch (MyException $e) { //MyException process here...}
Throwing an exception can do this:
$myException = new MyException(/*something here*/);throw $myException;
About the previous time, I mentioned a PHP exception handling mechanism problem, because the answer is very few, the author had to search the network resources and Danale articles (especially reference PHP core technology and Best practice book), now sorted as follows, if there are errors, welcome to point out:
In various languages, the concept of exceptions and errors is not the same, in PHP, any self-error will trigger an error, rather than throw an exception (for some cases, throw exceptions and errors!). )。 In this sense, it is impossible to deal with unpredictable situations like using exceptions. For example, it is not feasible to trigger an exception when the database connection is not open, which throws him as an error in PHP and is not automatically captured as an exception.
Classic except 0 questions:
try {$a = 5 / 0;echo $a;} catch (Exception $e) {echo $e->getMessage();$a = 123;}echo $a;
The output is:
PHP can catch exceptions only if you throw exceptions manually (typically, but there are PHP exceptions that can be automatically captured).
And for Java, it has a relatively perfect exception handling mechanism, all think of the abnormal situation as an exception, and PHP has taken them as a mistake, the root cause is that Java exception is the only way of error reporting, but in PHP is not the case. The popular point is that the designers of the two languages disagree on the definition of anomalies and errors, what is abnormal, what is wrong, and their designers have different views.
When you say the exception, you have to mention the unusual brother-----error in PHP. The error in PHP is much more valuable than the exception, and PHP provides a powerful error-handling function, please check your hand or network resources for details.