//trigger exception
checkNum(2);
?>
上面的代码会获得类似这样的一个错误: Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6 Try, throw 和 catch 要避免上面例子出现的错误,我们需要创建适当的代码来处理异常。 处理处理程序应当包括: Try - 使用异常的函数应该位于 "try" 代码块内。如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,会抛出一个异常。 Throw - 这里规定如何触发异常。每一个 "throw" 必须对应至少一个 "catch" 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 例子解释: 上面的代码抛出了一个异常,并捕获了它:
创建 checkNum() 函数。它检测数字是否大于 1。如果是,则抛出一个异常。 在 "try" 代码块中调用 checkNum() 函数。 checkNum() 函数中的异常被抛出 "catch" 代码块接收到该异常,并创建一个包含异常信息的对象 ($e)。 通过从这个 exception 对象调用 $e->getMessage(),输出来自该异常的错误消息
不过,为了遵循“每个 throw 必须对应一个 catch”的原则,可以设置一个顶层的异常处理器来处理漏掉的错误。 创建一个自定义的 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);
}
}
try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
throw new Exception("$email is an example e-mail");
}
}
try
{
try
{
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
//throw exception if email is not valid
throw new Exception($email);
}
}
catch(Exception $e)
{
//re-throw exception
throw new customException($email);
}
}