4

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?

devnull Ψ
  • 3,779
  • 7
  • 26
  • 43
  • 1
    because "Warning" is not an error. You can only catch exceptions that actually get thrown. So for this example you'll have to code your own verification that you actually got a file opened. – Jeff Aug 01 '16 at 14:42
  • 2
    read here how to "catch" a warning: http://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning – Jeff Aug 01 '16 at 14:45
  • 1
    Not every PHP statement/function throws Exceptions. You can only catch what is thrown – RiggsFolly Aug 01 '16 at 14:46

1 Answers1

3

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();
       }
     }
}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • thanks for reply. can you please tell me, if i have to add `@` and also check for false/null `if( !$this->file )` then whats the point of using try catch? it seems like i can check file with `if` operators without try catch and result would be the same – devnull Ψ Aug 01 '16 at 14:54
  • 1
    @მაზა ფაკა The `try{}catch` Block can be outside the class if you want, but that `if()` that you want to use can not outside the class. Read more into the Topic ExeptionHandling, ExeptionTypes UserDefinedExeptions :-) – JustOnUnderMillions Aug 01 '16 at 14:57
  • 1
    The `try-catch` block should be used outside the class, it's pretty useless within the method where you throw the exception. – Charlotte Dunois Aug 01 '16 at 14:57
  • I think i should go more deep in exceptions to know how the works. thank you guys – devnull Ψ Aug 01 '16 at 15:01