草庐IT

php - 新手 : throw new exception - can we change exception name?

coder 2024-04-23 原文

我正在尝试处理异常(exception)情况。

所以我有类似的东西:

如果发生不好的事情:

throw new CreateContactException($codigo, $result->msg);

稍后,我会尝试,如果不行,捕获:

try 
{
  createContact();
}
catch(CreateContactException $e) 
{
  $error .= 'An error occurred with the code:'.$e->getCode().' and message:'.$e->getMessage();
}

1) 这行得通吗?我的意思是,这个 getCode() 和 getMessage() 与 CreateContactException 参数无关,是吗?

2) 我必须在某处有一个扩展 Exception 的 CreateContactException 类吗?我的意思是,我们是否可以在不需要创建扩展类的情况下为异常设置自定义名称?

非常感谢, 内存

最佳答案

Exceptions 必须只是内置 Exception 类的子类,因此您可以像这样创建一个新的:

class CreateContactException extends Exception {}

尝试将其他类作为异常抛出会导致错误。

使用不同名称的一个优点是您可以有多个 catch block ,因此您可以捕获不同类型的异常并让其他异常通过:

try {
    // do something
}
catch (CreateContactException $e) {
    // handle this
}
catch (DomainException $e) {
    // handle this
}

关于php - 新手 : throw new exception - can we change exception name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3361576/

有关php - 新手 : throw new exception - can we change exception name?的更多相关文章

随机推荐