假设我有一个类,其方法如下:
/*
*
* Loads the user from username.
*
* @param string $username The username
*
* @return UserInterface
*
* @throws userNotFoundException if the user is not found
*/
public function getUser($username)
{
// someFunction return an UserInterface class if found, or null if not.
$user = someFunction('SELECT ....', $username);
if ($user === null) {
throw new userNotFoundException();
}
return $user
}
现在假设 someFunction
可能会因为 XYZ 原因抛出 InvalidArgumentException
/RuntimeException
/PDOException
。我应该怎么办? 还有什么不呢?
1 号
在 php-docs 中添加所有可能引发 someFunction
的异常。
/*
*
* Loads the user from username.
*
* @param string $username The username
*
* @return UserInterface
*
* @throws userNotFoundException if the user is not found
* @throws InvalidArgumentException
* @throws ...
*/
2号
添加一个 try-catch block 以确保该方法应仅在文档中引发异常
/*
*
* Loads the user from username.
*
* @param string $username The username
*
* @return UserInterface
*
* @throws userNotFoundException if the user is not found
* @throws RuntimeException
*/
public function getUser($username)
{
try {
$user = someFunction('SELECT ....', $username);
} catch (Exception $e) {
throw new RuntimeException();
}
if ($user === null) {
throw new userNotFoundException();
}
return $user
}
3 号
什么都别做。
最佳答案
我个人会考虑将 @throws
视为类似于 Java 的已检查异常
这在 Java 中的工作方式是基本上可以抛出从 RuntimeException 继承的异常,而不必处理。任何其他类型的异常都必须有一个 try-catch block 来处理它们。这个处理代码必须在调用者中。
在 PHP 中基本上是这样的:
当方法具有 @throws
注释时,您必须添加代码来处理其异常。
任何未提及的异常都是可选的,可在调用代码中处理。
现在,我自己并没有 100% 遵循这个原则。整个处理异常的事情有点取决于程序员的偏好,但这只是我认为如何以合理的方式处理它的一些想法。
关于php - 最佳实践 : Use of @throws in php-doc, 以及如何处理它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15587530/