PHP exception handling and error handling method sharing

Source: Internet
Author: User
Tags php error php exception handling
PHP Exception: is a logical and business process of an interruption, PHP errors: Their own problems, illegal grammar or environmental issues, the compiler can not pass the check, unable to run, this article is mainly to share with you PHP exception handling and error handling methods, I hope to help everyone.

How to use exception handling mechanisms

The difference between PHP and Java, except for the 0 exception

<?php/** * Created by Phpstorm. * User:wangkai * DATE:2018/3/6 * Time: Morning 8:53 * * $a =null;try{    $a =5/0;    echo $a;} catch (Exception $e) {    $e->getmessage ();    $a =-1;} echo $a;

Run results


Java implementation

public class excepetiontry{public    static void Tp () throws arithmeticexception{        int A;        a=5/0;        System.out.println ("Result of the operation:" +a);    }    public static void Main (string[] args) {        int A;        try{         a=5/0;         SYSTEM.OUT.PRINTLN ("Operation result" +a);        } catch (ArithmeticException e) {            e.printstacktrace ();        } finally{            a=-1;            SYSTEM.OUT.PRINTLN ("Operation result" +a);        }        try{            exceptiontry.tp ();        } catch (Exception e) {            System.out.println ("Exception caught");}}}}    

In PHP, think this is a mistake, directly trigger the error, does not automatically throw an exception, PHP only after the active throw, to catch the exception

In Java, it is assumed that except 0 belongs to ArithmeticException, it is captured and the exception is processed

To put it simply, PHP has made all the anomalies a mistake, using if else to catch exceptions, PHP's built-in exception class has pdoexception,reflection exception

Exceptions in Java are the only way to report errors

How to use PHP exceptions

1 Pessimistic predictions of the program

For example, deadlock problem in high concurrency condition, pessimistic throw problem

2 program requirements and business concerns

Upload files and save to database to ensure consistency of business data

Two ways of catching exceptions

Capture immediately when the first exception occurs

<?php try{//Possible error code snippet if (file upload is unsuccessful) throw (upload exception) if (insert database unsuccessful) throw (database operation exception)}catch (Exception) {required remedial action, such as delete file, delete database insert record}}

The second is the concentrated trapping of scattered parabolic anomalies.

<?php Upload {if (file upload not successful) throw (upload exception) if (insert data not successful) throw (Database operation exception)//other code try{upload, other;}catch (upload exception) {Necessary remedy, delete file, delete data insert record} catch (Other exception) {log log}

3 language-level robustness

1.6.2 How to see PHP exceptions

PHP's exception mechanism is insufficient, PHP needs to focus on what happened, Java is concerned about the exception of the capture and subsequent remediation

The best way to do this is to actively throw exceptions in conjunction with error handling in PHP

1.6.3 error levels in PHP

PHP Error: A scenario that causes the script to run abnormally

Errors in the following categories:

Deprecated the lowest level of errors, not recommended, not recommended, outdated functions or syntax caused by

Notice syntax where there are improper use of variables but not defined, the data index is a character without quotes, PHP will treat it as a constant, check the constant table

I can't find it, I'll see it as a wolf.

Warning is a high-level error, improper syntax, such as function parameters mismatch, this error to get the expected results

Fetal error fatal errors that directly lead to the end of the PHP process, the following code does not execute

Prase error parsing errors, which belong to the stage of the grammar check

Turn On error display, php.ini file settings

error_reporting=e_all| E_strict

Display_errors=on

When code quality or environment is not controllable, use error_reporting (0) or the function before the @

1.6.4 error handling mechanism in PHP

PHP has a set of error handling mechanisms, you can use Set_error_handler to take over PHP error handling

Set_error_handler (Error_function,error_types)

Error_function a function that runs when an error occurs, must

ERROR_TYPES Specifies the error report level at which the user-defined error is displayed, optional

<?php/** * Created by Phpstorm. * User:wangkai * DATE:2018/3/6 * Time: 10:03 *//user-defined error handler function MyErrorHandler ($errno, $errstr, $errfile, $err Line) {     echo "<b>custom error:</b> [$errno] $errstr <br>";     echo "Error on line $errline in $errfile <br>"; }//Set user-defined error handling function Set_error_handler ("MyErrorHandler"); $a =array (' O ' =>2,4,5,6); echo $a [o];?>

Actively throwing exception implementations


function Customerror ($errno, $errstr, $errfile, $errline) {throw new Exception ($level. $errstr);} Set_error_handler ("Customeerror"); try{$a =5/0;} catch (Exception $e) {echo "error message:". $e->getmessage ();}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.