簡體   English   中英

異常(嘗試,捕獲)如何在 php 中工作?

[英]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();
       }
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM