【问题标题】:Re-throw an exception in PHP在 PHP 中重新抛出异常
【发布时间】:2013-09-19 20:56:46
【问题描述】:

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

【问题讨论】:

  • 事先正确测试=没有错误:-),当然你可以只记录它们而不显示它们。或使用自定义错误处理程序。
  • 如果您尝试在 google 上搜索,您可能会发现一些有价值的信息。
  • 你读过the manual吗?
  • 只需记录您的 php 错误。
  • error_reporting(0) 有什么问题??这听起来有点矫枉过正——当然你应该处理异常,但你没有将它们展示给最终用户。

标签: php exception try-catch throw


【解决方案1】:

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

<?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();
  }
     ?>

示例说明: 上面的代码测试 email-address 中是否包含字符串“example”,如果包含,则重新抛出异常:

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

如果异常没有在其当前的“try”块中被捕获,它将在“更高级别”上搜索一个catch块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2011-12-26
    • 2011-10-10
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多