在 PHP 中,我有时会使用 try/catch 来捕获一些异常:
try {
...
} catch (Exception $e) {
// Nothing, this is a test that an exception is thrown.
}
使用这种代码,我最终得到了一个毫无意义的变量$e
(大量资源),而且PHP_MD(PHP混乱检测器)会因为未使用的变量而创建一个警告。
在 PHP 中,我有时会使用 try/catch 来捕获一些异常:
try {
...
} catch (Exception $e) {
// Nothing, this is a test that an exception is thrown.
}
使用这种代码,我最终得到了一个毫无意义的变量$e
(大量资源),而且PHP_MD(PHP混乱检测器)会因为未使用的变量而创建一个警告。
从PHP 8开始,可以使用非捕获catch语句。
这是相关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");
}
通过这种方式,在某些边缘情况下,如果异常细节不相关且异常类型已经提供所有必要的上下文,就可以在不创建新变量的情况下捕获异常。
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);
}
}
}
我假设您只是因为需要而不是想要才捕获异常。
在 PHP 5、7 中,如果您想使用 try
,就必须使用 catch
,如果您使用了 catch
,就必须声明一个变量。
这就是异常的全部意义 - 你可以有多个不同的catch块来捕获任何你想要处理的异常。异常的数据必须被分配到某个地方,因此需要一个变量。如果你真的不想看到这些警告,你可以在catch块内做一些类似于unset($e)
的操作... 或者禁用警告(通常不是一个好主意)。
try {
File::create($fileName);
}
// Go on with the rest of the code.
选项2(不使用try/catch):
if (!File::exists($fileName))
File::create($fileName);
不行。
无论如何,捕获异常后什么也不做通常都是一个坏主意;异常存在的目的就是为了强制你处理异常情况(否则执行将被中止),因此理解语言不支持这种用例。
从PHP 8.0开始,可以不使用变量对其进行类型化,但每个Exception
的一般情况现在是Throwable
。类Exception
实现了Throwable
。
try {
...
} catch (CustomException) {
// CustomException
} catch (Throwable) {
//All other classes implementing Throwable interface
}
throw
。这里假设readFile()
会throw
任何异常,因此被包裹在一个try/catch
块中。 - undefined