加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-26 02:20:18 所属栏目:PHP 来源:互联网
导读:我使用try-catch多年,但我从来没有学到如何和什么时候使用终于,因为我从来没有明白的点终于(我读坏书)? 我想问你最后在我的情况下的使用. 我的代码示例应该解释一切: $s = ;$c = MyClassForFileHandling::getInstance();try{ $s = $c-get_file_content($pat

我使用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();
    }
}

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

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读