作者:mobiledu2502937981 | 来源:互联网 | 2018-03-21 05:00
在php中错误处理的方法有很多,特别是到了php5之后还提供了专门的php处理类,下面我收藏了关于PHP错误处理一些方法与程序分享给大家.在程序中直接判断,基本的错误处理:使用die()函数...
在php中错误处理的方法有很多,特别是到了php5之后还提供了专门的php处理类,下面我收藏了关于PHP错误处理一些方法与程序分享给大家.
在程序中直接判断,基本的错误处理:使用 die() 函数,第一个例子展示了一个打开文本文件的简单脚本,代码如下:
如果文件不存在,您会获得类似这样的错误:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:webfoldertest.php on line 2
更多详细的,代码如下:
第二种:错误处理器 错误级别 处理错误方式,代码如下:
$errno"; //输出错误报告级别
echo "错误信息是:" . $errmes;
exit();
}
function my_error2($errno, $errmes) {
//echo "错误信息是:".$errno,$errmes;
//exit();
//把错误信息输入到文本中保存已备查看 使用到error_log()函数
$message = "错误信息是:" . $errno . " " . $errmes;
error_log(date("Y-m-d G:i:s") . "---" . $message . "rn", 3, "myerror.txt"); // rn 表示换行
}
//打开一个文件 未做任何处理
//$fp =fopen("aa.txt","r");
//echo "OK";
//使用自定义错误 要添加触发器 这个trigger_error()函数来指定调用自定义的错误
$age = 200;
if ($age > 150) {
//echo "年龄过大";
//调用触发器 同时指定错误级别 这里需要查看帮助文档
trigger_error("不好了出大问题了", E_USER_ERROR);
//exit();
}
?>
PHP 异常处理,PHP 5 提供了一种新的面向对象的错误处理方法
如果异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么将发生一个严重的错误(致命错误),并且输出 "Uncaught Exception" (未捕获异常)的错误消息.
让我们尝试抛出一个异常,同时不去捕获它,代码如下:
1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
上面的代码会获得类似这样的一个错误:
Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:webfoldertest.php:6 Stack trace: #0 C:webfoldertest.php(12): checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6Try, throw 和 catch
要避免上面例子出现的错误,我们需要创建适当的代码来处理异常.
处理处理程序应当包括:
1.Try - 使用异常的函数应该位于 "try" 代码块内,如果没有触发异常,则代码将照常继续执行,但是如果异常被触发,会抛出一个异常。
2.Throw - 这里规定如何触发异常,每一个 "throw" 必须对应至少一个 "catch"
3.Catch - "catch" 代码块会捕获异常,并创建一个包含异常信息的对象.
让我们触发一个异常,代码如下:
1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//在 "try" 代码块中触发异常
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//捕获异常
catch(Exception $e) {
echo 'Message: ' . $e->getMessage();
}
?>
上面代码将获得类似这样一个错误:Message: Value must be 1 or below
创建一个自定义的 Exception 类,创建自定义的异常处理程序非常简单,我们简单地创建了一个专门的类,当 PHP 中发生异常时,可调用其函数,该类必须是 exception 类的一个扩展.
这个自定义的 exception 类继承了 PHP 的 exception 类的所有属性,您可向其添加自定义的函数.
我们开始创建 exception 类,代码如下:
getLine() . ' in ' . $this->getFile() . ': ' . $this->getMessage() . ' is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example...com";
try {
//check if
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch(customException $e) {
//display custom message
echo $e->errorMessage();
}
?>
这个新的类是旧的 exception 类的副本,外加 errorMessage() 函数,正因为它是旧类的副本,因此它从旧类继承了属性和方法,我们可以使用 exception 类的方法,比如 getLine() 、 getFile() 以及 getMessage().
本文地址:
转载随意,但请附上文章地址:-)