gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:20:54 24 4
gpt4 key购买 nike

我使用 try-catch 很多年了,但我从来没有学会如何以及何时使用 finally,因为我从来不理解 finally< 的意义(我读过烂书)?

我想问你关于在我的案例中使用 finally 的问题。

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

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

finally 的用法正确吗?

更精确的问题:

我是否应该使用 finally(在未来的 PHP 版本或其他语言中)来处理“创建不存在的东西”操作?

最佳答案

Finally 总是会被执行,所以在这种情况下,这不是它的预期目的,因为正常执行会再次重新打开文件。如果你这样做,你打算做的事情将以相同的(更干净的)方式实现

$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

finally 在这种情况下会很有用:

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 - 我可以像这样使用 try-catch-finally 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15031515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com