【发布时间】:2024-01-22 18:32:01
【问题描述】:
我不完全了解异常是如何工作的。正如我所假设的,他们应该避免 php 错误并显示“我的错误消息”。比如我要打开文件
class File{
public $file;
public function __construct($file)
{
try{
$this->file = fopen($file,'r');
}
catch(Exception $e){
echo "some error" . $e->getMessage();
}
}
}
$file = new File('/var/www/html/OOP/texts.txt');
它有效。现在我故意将文件名 texts.txt 更改为 tex.txt 只是为了从我的 catch 块中看到一条错误消息,但是,php 给出了一个错误 Warning: fopen(/var/www/html/OOP/texts.txt): failed to open stream: No such file or directory in /var/www/html/OOP/file.php on line 169 。所以这是 php 错误,它不会显示来自 catch 块的错误消息。我究竟做错了什么? try/catch 究竟是如何工作的?
【问题讨论】:
-
因为“警告”不是错误。您只能捕获实际抛出的异常。因此,对于此示例,您必须编写自己的代码来验证您确实打开了文件。
-
在这里阅读如何“捕捉”警告:*.com/questions/1241728/can-i-try-catch-a-warning
-
不是每个 PHP 语句/函数都会抛出异常。你只能抓住抛出的东西