php高级教程(2)
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$th
php高级教程 class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->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); } //check for "example" in mail address 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(); } 重新抛出异常 有时,当异常被抛出时php实例教程,您也许希望以不同于标准的方式对它进行处理。可以在一个 "catch" 代码块中再次抛出异常。 class customException extends Exception { public function errorMessage() { //error message $errorMsg = $this->getMessage().' is not a valid E-Mail address.'; return $errorMsg; } } $email = "someone@example.com"; try { try { //check for "example" in mail address if(strpos($email, "example") !== FALSE) { //throw exception if email is not valid throw new Exception($email); //抛出Exception异常 } } catch(Exception $e) //捕获Exception异常 { //re-throw exception throw new customException($email); //抛出customException异常 } } catch (customException $e) //捕获customException异常 { //display custom message echo $e->errorMessage(); } 设置顶层异常处理器 (Top LevelException Handler) set_exception_handler() 函数可设置处理所有未捕获异常的用户定义函数。 function myException($exception) { echo "Exception: " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); 在上面的代码中,不存在 "catch" 代码块,而是触发顶层的异常处理程序。应该使用此函数来捕获所有未被捕获的异常。 异常的规则 ·需要进行异常处理的代码应该放入 try 代码块内,以便捕获潜在的异常。 ·每个 try 或 throw 代码块必须至少拥有一个对应的 catch 代码块。 ·使用多个 catch 代码块可以捕获不同种类的异常。 ·可以在 try 代码块内的 catch 代码块中再次抛出(re-thrown)异常。 简而言之:如果抛出了异常,就必须捕获它。 七、PHP Include 文件 服务器端包含 (SSI) 用于创建可在多个页面重复使用的函数、页眉、页脚或元素。 PHP include 和 require 语句 通过 include 或 require 语句,可以将 PHP 文件的内容插入另一个 PHP 文件(在服务器执行它之前)。 include 和 require 语句是相同的,除了错误处理方面: ·require 会生成致命错误(E_COMPILE_ERROR)并停止脚本 ·include 只生成警告(E_WARNING),并且脚本会继续 语法 include 'filename'; 或 require 'filename'; PHP include 实例 例子 1 假设我们有一个名为 "footer.php" 的标准的页脚文件,就像这样: echo " (编辑:威海站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |