二、error_reporting() 及 try-catch、thrown
error_reporting() 函数可以获取(不传参时)、设定脚本处理哪些异常(并非所有异常都需要处理,例如 E_CORE_WARNING、E_NOTICE、E_DEPRECATED 是可以忽略的),该设定将覆盖 php.ini 中 error_reporting选项定义的异常处理设定。
例如:
error_reporting(E_ALL&~E_NOTICE) ; // 除了E_NOTICE其他异常都会被触发(E_ALL&~E_NOTICE的二进制运算结果是:E_NOTICE对应位的值被设置为0)
try-catch 无法在类的自动加载函数 __autoload() 内生效。
try-catch 无法用于捕获异常,无法捕获错误,例如 trigger_error() 触发的错误,异常和错误是不一样的。
try{
// you codes that maybe cause an error
}catch(Exception $err){ // 这个错误对象需要声明类型, Exception 是系统默认异常处理类
echo $err->getMessage();
}
//thrown 可以抛出一个异常,如:
thrown new Exception('an error');
一个例子:
try {
if ( empty( $var1 ) ) throw new NotEmptyException();
if ( empty( $var2 ) ) throw new NotEmptyException();
if ( ! preg_match() ) throw new InvalidInputException();
$model->write();
$template->render( 'success' );
} catch ( NotEmptyException $e ) {
$template->render( 'error_empty' );
} catch ( InvalidInputException $e ) {
$template->render( 'error_preg' );
}
Exception 类的结构:其中大部分方法都是 禁止改写的(final )
Exception {
/* 属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 方法 */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = null]]] )
final public string getMessage ( void ) //异常抛出的信息
final public Exception getPrevious ( void ) //前一异常
final public int getCode ( void ) //异常代码,这是用户自定义的
final public string getFile ( void ) //发生异常的文件路劲
final public int getLine ( void ) //发生异常的行
final public array getTrace ( void ) //异常追踪信息(array)
final public string getTraceAsString ( void ) //异常追踪信息(string)
public string __toString ( void ) //试图直接 将异常对象当作字符串使用时调用子函数的返回值
final private void __clone ( void ) //克隆异常对象时调用
}
扩展异常类
try-catch 可以有多个 catch 子句,从第一个 catch 子句开始,如果子句内的 异常变量 类型匹配 thrown 语句抛出的异常类型,则该子句会被执行而不再执行其他catch子句,否则继续尝试下一个 catch 子句,由于Exception 是所有 异常类的基类,因此抛出的异常都会与他匹配 ,如果你像个根据不同异常类型使用不同的处理方法,应该将 Exception 类型的 catch 子句放到最后。
Exception 是所有异常的基类,可以根据实际需要扩展异常类,
calss MyException extends Exception{
public errType = 'default';
public function __construct($errType=''){
$this->errType = $errType;
}
}
thrown new MyException (); //抛出一个异常
try{
// you codes that maybe cause an error
}catch(MyException $err){ // 这个错误对象需要声明类型
echo $err->errType();
}catch(ErrorException $err){ //ErrorException 是 PHP 5 增加的异常类,继承于 Exception
echo 'error !';
}catch(Exception $err){
redirect('/error.php');
}
你可能会在 catch 子句中判断异常的类型,或者根据 code 等信息来决定是否处理异常,如果你卸载 catch 子句的代码无法适当的处理捕获的异常,你可以在 catch 子句内继续 抛出异常。
本文导航
- 第1页: 首页
- 第2页: try-catch
- 第3页: Exception 异常的回调函数