მაზა ფაკა მაზა ფაკა - 4 months ago 19
PHP Question

how exceptions(try, catch) work in php?

I don't exactly know how exceptions work. as I assume, they should avoid php errors and display "my error message". for example, i want to open 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');


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 php error, it doesn't display error message from catch block. What am I doing wrong? how exactly try/catch works?

Answer

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