Home  >  Article  >  Backend Development  >  php exception handling class

php exception handling class

WBOY
WBOYOriginal
2016-08-08 09:29:03891browse

PHP has many exception handling classes, among which Exception is the base class for all exception handling.

Exception has several basic properties and methods, including:

message exception message content
code exception code
file file name where the exception was thrown
line line number of the file where the exception was thrown

The commonly used methods are:

getTrace Gets exception tracing information
getTraceAsString Gets the string of exception tracing information
getMessage Gets error information

If necessary, you can create a custom exception handling class by inheriting the Exception class.

//自定义的异常类,继承了PHP的异常基类Exception
class MyException extends Exception {
    function getInfo() {
        return '自定义错误信息';
    }
}

try {
    //使用异常的函数应该位于 "try"  代码块内。如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,会抛出一个异常。
    throw new MyException('error');//这里规定如何触发异常。注意:每一个 "throw" 必须对应至少一个 "catch",当然可以对应多个"catch"
} catch(Exception $e) {//"catch" 代码块会捕获异常,并创建一个包含异常信息的对象
    echo $e->getInfo();//获取自定义的异常信息
    echo $e->getMessage();//获取继承自基类的getMessage信息
}

The above introduces the PHP exception handling class, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn