Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP try catch block does not catch

I would like to open a file in PHP and the first thing I do is a check to see if it exists. Because of this I'm adding it to a a try catch block, so the script does not collapse. If the file does not exist the script should stop. The code below is giving an error message the file could not be opened.

(The file does not exist, for testing reasons)

    try
    {
        $file_handle = fopen("uploads/".$filename."","r");
    }
    catch (Exception $hi)
    {
        die("Fehler");
    }

This is the error displayed in my browser:

Warning: fopen(uploads/Testdatensatz_Bewerbungenn.csv): failed to open stream: No such file or directory in [...]\bewerbungToDB.php on line 11

like image 214
JRsz Avatar asked Jan 31 '15 20:01

JRsz


People also ask

Does exception catch all exceptions PHP?

Catching all PHP exceptions Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front: try { // ... }

What happens when a catch block is not given?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.

Does try catch stop execution PHP?

Try catch in PHP is a block that contains the program's vital code for execution. In PHP, the finally block is also used to clean up the code. The only difference is that it always runs regardless of whether or not an exception is thrown.

Which is the correct way to use catch block in PHP?

The “try” block is executed and an exception is thrown if the denominator is zero or negative number. The “catch” block catches the exception and displays the error message. The flowchart below summarizes how our sample code above works for custom types of exceptions.


1 Answers

That's not an exception. It's a PHP warning. Try/catch is for catching exceptions only. If you want to "catch" that error you should check the value of $file_handle and if it is false throw an exception.

try
{
    $file_handle = @fopen("uploads/".$filename."","r");
    if (!$file_handle) {
         throw new Exception('Failed to open uploaded file');
    }
}
catch (Exception $hi)
{
    die("Fehler");
}
like image 144
John Conde Avatar answered Oct 19 '22 00:10

John Conde