简体   繁体   English

PHP try catch块没有捕获

[英]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. 我想用PHP打开一个文件,我要做的第一件事是检查它是否存在。 Because of this I'm adding it to aa try catch block, so the script does not collapse. 因此我将它添加到try catch块中,因此脚本不会崩溃。 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 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 警告:fopen(uploads / Testdatensatz_Bewerbungenn.csv):无法打开流:第11行的[...] \\ bewerbungToDB.php中没有此类文件或目录

That's not an exception. 那不是例外。 It's a PHP warning. 这是一个PHP警告。 Try/catch is for catching exceptions only. Try / catch仅用于捕获异常。 If you want to "catch" that error you should check the value of $file_handle and if it is false throw an exception. 如果你想“捕获”那个错误,你应该检查$file_handle的值,如果是false则抛出异常。

try
{
    $file_handle = @fopen("uploads/".$filename."","r");
    if (!$file_handle) {
         throw new Exception('Failed to open uploaded file');
    }
}
catch (Exception $hi)
{
    die("Fehler");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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