gpt4 book ai didi

php - 异常(尝试,捕获)如何在 php 中工作?

转载 作者:行者123 更新时间:2023-12-04 12:46:25 26 4
gpt4 key购买 nike

我不完全知道异常是如何工作的。正如我所假设的,他们应该避免 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.txttex.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 究竟是如何工作的?

最佳答案

来自 PHP 手册

If the open fails, an error of level E_WARNING is generated. You may use @ to suppress this warning.


fopen出错时返回 FALSE,因此您可以对此进行测试并抛出将被捕获的异常。一些 native PHP 函数会产生异常,而另一些则会引发错误。
class File{
public $file;

public function __construct($file){
try{

$this->file = @fopen($file,'r');
if( !$this->file ) throw new Exception('File could not be found',404);

} catch( Exception $e ){
echo "some error" . $e->getMessage();
}
}
}

关于php - 异常(尝试,捕获)如何在 php 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38701623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com