在 PHP 中重新抛出异常


Re-throw an exception in PHP

我正在开发一个计算某些值的内部网站。我需要用简单的消息而不是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",如果包含,则会重新抛出异常:

  1. customException() 类是作为旧异常类的扩展创建的。这样,它继承了旧异常类的所有方法和属性
  2. 创建 errorMessage() 函数。如果电子邮件地址无效,此函数将返回错误消息
  3. $email变量设置为字符串,该字符串是有效的电子邮件地址,但包含字符串"example"
  4. "try"块
  5. 包含另一个"try"块,以便可以重新抛出异常
  6. 由于电子邮件包含字符串"example",因此触发了异常
  7. "
  8. catch"块捕获异常并重新抛出"customException"
  9. 捕获"自定义异常"并显示错误消息

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