PHP:捕获异常后是否可以恢复try块? [英] PHP: is it possible to resume the try block after the exception is caught?

查看:80
本文介绍了PHP:捕获异常后是否可以恢复try块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的代码:

try{
    doTaskA(); 
    doTaskB(); 
    doTaskC();
} catch(MyException $e){
    fixMyException();
}

当doTaskA()抛出MyException时,我希望程序通过fixMyException( ),然后返回并继续执行doTaskB()和doTaskC()。

When doTaskA() throws MyException, I want the program to go through fixMyException(), then it goes back and continues executing doTaskB() and doTaskC(). Is it possible?

同样的事情也应适用于其他任务,即所有doTaskA / B / C()都可能抛出相同的异常,我希望程序可以执行

The same thing should apply to other tasks, i.e. all doTaskA/B/C() may throw the same exception, and I want the program can go on to the unfinished tasks every time after it executes fixMyException()..

在异常处理中是否存在诸如 continue或 resume功能之类的东西?

Is there any thing like "continue" or "resume" function in the exception handling?

我检查了PHP手册,但似乎不存在这种控制结构。如果是这样,那么设计可满足我期望的程序的最佳实践是什么? (假设我在try块中有10个以上的任务)。

I have checked the PHP manual but it seems such control structure doesn't exist. If so, what's the best practice to design the program that can do what I want? (Supposed I have over 10 taskes inside the try block).

推荐答案

function do_all_tasks($position=0)
{
  $tasks = array('doTaskA', 'doTaskB', 'doTaskC', ...);
  $size  = count($tasks);
  for ($i=$position; $i<$size; ++$i)
  {
    try
    {
      $func = $tasks[$i];
      $func();
    }
    catch (Exception $e)
    {
      fixMyException();
      do_all_tasks($i+1);
    };
  }
}

do_all_tasks();

这篇关于PHP:捕获异常后是否可以恢复try块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆