Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中重新引发异常_Php_Exception_Try Catch_Throw - Fatal编程技术网

在PHP中重新引发异常

在PHP中重新引发异常,php,exception,try-catch,throw,Php,Exception,Try Catch,Throw,我正在开发一个计算某些值的内部网站。 我需要用简单的消息而不是PHP错误向用户显示计算中的错误。 我还在学习PHP中的抛出异常 在这种情况下,这是重新抛出异常的好方法吗 是的,这是可能的,也是一个好方法 <?php class customException extends Exception { public function errorMessage() { //error message $errorMsg = $this->getMessag

我正在开发一个计算某些值的内部网站。 我需要用简单的消息而不是PHP错误向用户显示计算中的错误。 我还在学习PHP中的抛出异常
在这种情况下,这是重新抛出异常的好方法吗

是的,这是可能的,也是一个好方法

<?php
 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);
      }
    }
  catch(Exception $e)
    {
    //re-throw exception
    throw new customException($email);
    }
  }

catch (customException $e)
  {
  //display custom message
  echo $e->errorMessage();
  }
     ?>

示例说明: 上面的代码测试电子邮件地址中是否包含字符串“example”,如果包含,将重新引发异常:

  • customException()类是作为旧异常类的扩展创建的。通过这种方式,它从旧的异常类继承所有方法和属性
  • 将创建errorMessage()函数。如果电子邮件地址无效,此函数将返回错误消息
  • $email变量设置为一个字符串,该字符串是有效的电子邮件地址,但包含字符串“example”
  • “try”块包含另一个“try”块,可以重新抛出异常
  • 由于电子邮件包含字符串“example”,因此会触发异常
  • “catch”块捕获异常并重新抛出“customException”
  • 捕获“customException”并显示错误消息

  • 如果异常未在其当前“try”块中捕获,它将在“更高级别”上搜索捕获块。

    正确的手前测试=无错误:-),当然您可以只记录它们而不显示它们。或者使用自定义错误处理程序。如果你尝试在谷歌上搜索,你可能会发现一些有价值的信息。你读了吗?只需记录你的php错误。有什么问题??这听起来有些过分——当然你应该处理异常,但你不必向最终用户展示它们。