phpexceptiontry-catch

Why I a fopen() error cannot be handled with try catch?


I don't exactly know how exceptions work. I assume, they should avoid php errors and display "my error message". For example, I want to open a file:

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');

and it works. Now I intentionally change the file name texts.txt to tex.txt just to see an error message from my catch block, but instead, php gives an error 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 . So it's a php error, but it doesn't display an error message from catch block. What am I doing wrong? How exactly does try/catch work?


Solution

  • From the PHP manual

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

    fopen returns FALSE on error so you could test for that and throw an exception which would be caught. Some native PHP functions will generate exceptions, others raise errors.

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