简体   繁体   中英

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 aa 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM