0

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

4

1 回答 1

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

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

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

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

于 2013-09-19T21:05:39.677 回答