php中的异常(try,catch)是如何工作的


how exceptions(try, catch) work in php?

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

来自PHP手册

如果打开失败,则会生成E_WARNING级别的错误。你可以使用@可以取消显示此警告。

fopen在出现错误时返回FALSE,这样您就可以测试它并抛出一个将被捕获的异常。一些本机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();
       }
     }
}