php – 我可以这样使用try-catch-finally吗?

前端之家收集整理的这篇文章主要介绍了php – 我可以这样使用try-catch-finally吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用try-catch多年,但我从来没有学到如何和什么时候使用终于,因为我从来没有明白的点终于(我读坏书)?

我想问你最后在我的情况下的使用.

我的代码示例应该解释一切:

$s = "";

$c = MyClassForFileHandling::getInstance();

try
{
    $s = $c->get_file_content($path);
}

catch FileNotFoundExeption
{
    $c->create_file($path,"text for new file");
}

finally
{
    $s = $c->get_file_content($path);
}

问题是:

这是正确的用法吗?

编辑:更精确的问题:

我最后会使用(以后的PHP版本或其他语言)来处理“创建一些如果不存在”操作?

最终总是执行,所以在这种情况下,这不是它的预期目的,因为正常的执行会再次打开文件.如果你这样做,你打算做的就是以同样(更清洁)的方式实现
$s = "";

$c = MyClassForFileHandling::getInstance();

try
{
    $s = $c->get_file_content($path);
}
catch(FileNotFoundExeption $e)
{
    $c->create_file($path,"text for new file");
    $s = $c->get_file_content($path);
}

然后手册说:

For the benefit of someone anyone who hasn’t come across finally blocks before,the key difference between them and normal code following a try/catch block is that they will be executed even the try/catch block would return control to the calling function.

It might do this if:

  • code if your try block contains an exception type that you don’t catch
  • you throw another exception in your catch block
  • your try or catch block calls return

那么最后在这种情况下会是有用的:

function my_get_file_content($path)
{
    try
    {
        return $c->get_file_content($path);
    }
    catch(FileNotFoundExeption $e)
    {
        $c->create_file($path,"text for new file");
        return $c->get_file_content($path);
    }
    finally
    {
        $c->close_file_handler();
    }
}

=>如果您需要确保在这种情况下关闭文件处理程序,或者一般的资源.

猜你在找的PHP相关文章