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);
}
然后手册说:
那么最后在这种情况下会是有用的: 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();
}
}
=>如果您需要确保在这种情况下关闭文件处理程序,或者一般的资源. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
