最基础的异常处理
try、catch、throw
<?php
function checkNum($number){
if($number>1){
throw new Exception("Value must be 1 or below");
}
return true;
}
try{
checkNum(2);
echo 'If you see this, the number is 1 or below';
}catch(Exception $e){
echo 'Message: ' .$e->getMessage();
}
自定义异常处理
<?php
// 异常类中只有构造函数和 __toString 类可以覆盖,其他函数都是 final 类型。
class customException extends Exception{
public function errorMessage(){
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example...com";
try {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
throw new customException($email);
}
}catch (customException $e) {
echo $e->errorMessage();
}
多个异常
// 捕捉到其中一个异常,就不会捕捉下面的
<?php
class customException extends Exception{
public function errorMessage(){
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example.com";
try {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
throw new customException($email);
}
if(strpos($email, "example") !== FALSE) {
throw new Exception("$email is an example e-mail");
}
}catch (customException $e) {
echo $e->errorMessage();
}catch(Exception $e) { //基类应放在最下面
echo $e->getMessage();
}
set_exception_handler
<?php
function myException($exception){
echo "Exception: " , $exception->getMessage();
}
set_exception_handler('myException'); //错误和异常最终都会指向这个函数
throw new Exception('Uncaught Exception occurred');
//后面的代码不执行
//输出:Exception: Uncaught Exception occurred
trigger_error
<?php
$divisor=0;
if ($divisor == 0) {
trigger_error("Cannot divide by zero!!!!!!!!!!", E_USER_ERROR);
}
//Fatal error: Cannot divide by zero!!!!!!!!!! in F:\WWW\l.php on line 4