在PHP中,我有时会使用try/catch捕获一些异常:
try {
...
} catch (Exception $e) {
// Nothing, this is normal
}有了这样的代码,我最终得到的是一个无用的变量$e (大量资源),而PHP_MD (PHP脏乱检测器)会因为一个未使用的变量而创建一个警告。
发布于 2020-05-15 00:16:25
从PHP 8开始,可以使用非捕获catch。
This is the relevant RFC,以48比1的赞成票。
现在可以这样做了:
try {
readFile($file);
} catch (FileDoesNotExist) {
echo "File does not exist";
} catch (UnauthorizedAccess) {
echo "User does not have the appropriate permissions to access the file";
log("User attempted to access $file");
}这样,对于异常细节不相关并且异常类型已经提供了所有必要上下文的一些边缘情况,可以在不创建新变量的情况下捕获异常。
发布于 2015-02-06 20:25:35
PHP 5,7
不能,但你可以取消设置。
try {
...
} catch (Exception $e) {
// Nothing, this is normal
unset($e);
}如果是PHPMD导致了这个问题,那么您可以禁止显示该警告。
class Bar {
/**
* This will suppress UnusedLocalVariable
* warnings in this method
*
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
public function foo() {
try {
...
} catch (Exception $e) {
// Nothing, this is normal
unset($e);
}
}
}我假设你只是捕获异常,因为你不需要这样做,因为你想这样做。在PHP5,7中,如果你想使用try,你必须使用catch,如果你使用catch,你必须声明一个变量。
发布于 2011-01-28 02:21:57
这就是异常的全部意义--你可以有多个不同的catch块来捕捉你想要处理的任何异常。异常的数据必须被赋值到某个地方,因此变量。如果你真的不想看到这些警告,你可以在catch代码块中执行类似unset($e)的操作……或者禁用警告(通常不是一个好主意)。
https://stackoverflow.com/questions/4820211
复制相似问题