PHP 异常和错误处理:错误级别 Draft
什么是 PHP 错误?
属于 PHP 脚本自身的问题,大部分情况是由错误的语法,或服务器环境导致编译器无法通过检查,甚至无法运行。warning
、notice
都是错误,只是他们的级别不同。
错误级别概览
E_ERROR
致命错误,会在页面显示 Fatal Error。 当出现这种错误时,程序无法继续执行。
// Fatal error: Call to undefined function hpinfo() in /tmp/php/index.php on line 5
hpinfo(); //E_ERROR
如果有未被捕获的异常,也会触发这个级别的错误。
// Fatal error: Uncaught exception 'Exception' with message 'test exception' in /tmp/php/index.php:5 Stack trace: #0 {main} thrown in /tmp/php/index.php on line 5
throw new \Exception("test exception");
E_WARNING
警告,显示的错误信息是 Warning。不会终止脚本,程序还会继续进行。比如 include
一个不存在的文件。
//Warning: include(a.php): failed to open stream: No such file or directory in /tmp/php/index.php on line 7
//Warning: include(): Failed opening 'a.php' for inclusion (include_path='.:/usr/share/pear:/usr/share/php') in /tmp/php/index.php on line 7
include("a.php"); //E_WARNING
E_NOTICE
错误程度较轻微,提示某个地方不应该这么写。属于运行时的错误,错误的代码可能在其他地方没有问题,只是在当前上下文情况下出现了问题。
比如 $b
变量不存在,我们把它赋值给另外一个变量。
//Notice: Undefined variable: b in /tmp/php/index.php on line 9
$a = $b; //E_NOTICE
E_PARSE
在编译期发现语法错误,不能进行语法分析。
比如下面的 z
没有设置为变量。
// Parse error: syntax error, unexpected '=' in /tmp/php/index.php on line 20
z = 1; // E_PARSE
E_STRICT
PHP 5 之后引入的错误,代码可以运行,但不是 PHP 建议的写法。
比如在函数参数中使用 ++
符号
// Strict Standards: Only variables should be passed by reference in /tmp/php/index.php on line 17
function change (&$var) {
$var += 10;
}
$var = 1;
change(++$var); // E_STRICT
E_RECOVERABLE_ERROR
ERROR 级别的错误,理论上是应该被捕获的,一旦没有被错误处理捕获,表现和 E_ERROR 一样。
经常出现在形参定义了类型,但调用的时候传入了错误类型。它的错误提醒比 E_ERROR 的 fatal error 前面多了一个 Catachable 的字样。
//Catchable fatal error: Argument 1 passed to testCall() must be an instance of A, instance of B given, called in /tmp/php/index.php on line 37 and defined in /tmp/php/index.php on line 33
class A {
}
class B {
}
function testCall(A $a) {
}
$b = new B();
testCall($b);
E_DEPRECATED
表示用了旧版本的函数,而这个函数后期版本可能被禁用或者不维护了。
比如 curl
的 CURLOPT_POSTFIELDS
使用 @FILENAME
上传文件的方法。
// Deprecated: curl_setopt(): The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead in /tmp/php/index.php on line 42
$ch = curl_init("http://www.remotesite.com/upload.php");
curl_setopt($ch, CURLOPT_POSTFIELDS, array('fileupload' => '@'. "test"));
E_CORE_ERROR, E_CORE_WARNING
由 PHP 的引擎产生的错误,发生在 PHP 初始化过程中。
E_COMPILE_ERROR, E_COMPILE_WARNING
由 PHP 引擎产生的错误,发生在编译过程中。
E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_USER_DEPRECATED,
用户制造的错误,使用 trigger_error,这里就相当于一个入口给用户触发出各种错误类型。这个是一个很好逃避try catch
异常的方式。
trigger_error("Cannot divide by zero", E_USER_ERROR);
// E_USER_ERROR
// E_USER_WARING
// E_USER_NOTICE
// E_USER_DEPRECATED
E_ALL
E_STRICT 除外的所有错误和警告信息。
以上,是按照错误级别划分的 PHP 的 16 种错误。