gpt4 book ai didi

php - `finally` 何时以及为何有用?

转载 作者:可可西里 更新时间:2023-11-01 12:53:21 24 4
gpt4 key购买 nike

PHP 5.5 实现了 finallytry-catch。我的疑问是:什么时候 try-catch-finally 可能比我在下面写的 try-catch 更有用?

例子,区别:

try { something(); }
catch(Exception $e) { other(); }
finally { another(); }

而不是,只是:

try { something(); }
catch(Exception $e) { other(); }
another();

可以给我一些这个案例中常见的例子吗?

注意事项:

  1. 我只谈论try-catch-finally,而不是try-finally
  2. 有些“功能”很酷,比如取消当前异常并在 finally 上抛出一个新的其他异常(我没试过,I read here)。我不知道如果没有 finally;
  3. 是否可行
  4. notcatch 这样的东西不是更有用吗?因此,如果 try 没有异常,我就可以运行代码。呵呵

最佳答案

finally block 中的代码总是在离开 trycatch block 后执行。当然,您可以在 try-catch 之后继续编写代码,它也会被执行。但当您想中断代码执行时(例如从函数返回、中断循环等),finally 可能很有用。您可以在此页面上找到一些示例 - http://us2.php.net/exceptions ,例如:

function example() {
try {
// open sql connection
// Do regular work
// Some error may happen here, raise exception
}
catch (Exception $e){
return 0;
// But still close sql connection
}
finally {
//close the sql connection
//this will be executed even if you return early in catch!
}
}

但是,是的,你是对的; finally 在日常使用中不是很流行。当然不如单独使用 try-catch 多。

关于php - `finally` 何时以及为何有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22597434/

24 4 0