Is there a way to catch an Exception without having to create a variable?(有没有一种方法可以在不创建变量的情况下捕获异常?)
问题描述
在PHP中,我有时使用try/catch:
捕获一些异常try {
...
} catch (Exception $e) {
// Nothing, this is normal
}
使用这种代码,我最终得到的变量$e
是无用的(大量资源),PHP_MD(PHP乱七八糟的检测器)会因为一个未使用的变量而创建警告。
推荐答案
从PHP8开始,可以使用非捕获捕获。
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");
}
这样,对于异常详细信息不相关并且异常类型已提供所有必要上下文的某些边缘情况,无需创建新变量即可捕获异常。
这篇关于有没有一种方法可以在不创建变量的情况下捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!