让我们尝试抛出一个异常,同时不去捕获它: 复制代码 代码如下: <?php //create function with an exceptionfunction checkNum($number) { if($number>1) { throw new Exception(”Value must be 1 or below”); } return true; } //trigger exceptioncheckNum(2); ?>
上面的代码会获得类似这样的一个错误:
Fatal error: Uncaught exception ‘Exception" with message ‘Value must be 1 or below" in C:webfolder est.php:6 Stack trace: #0 C:webfolder est.php(12): checkNum(28) #1 {main} thrown in C:webfolder est.php on line 6 Try, throw 和 catch 要避免上面例子出现的错误,我们需要创建适当的代码来处理异常。
<?php//创建可抛出一个异常的函数function checkNum($number) { if($number>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 class customException extends Exception { public function errorMessage() { //error message $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 { //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(); }?>
可以使用多个 if..else 代码块,或一个 switch 代码块,或者嵌套多个异常。这些异常能够使用不同的 exception 类,并返回不同的错误消息: 复制代码 代码如下: <?php class customException extends Exception{public function errorMessage(){ //error message$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 { //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(); }?>