0

Let's say I have codes like this:

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

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?

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()..

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

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).

LazNiko
  • 2,083
  • 3
  • 25
  • 39
  • You seem to be missing the point of exceptions here. An exception is something well, exceptional, that warrants interrupting execution of the code (and skipping the rest of the `try` block) and go to the exception handler. It's not supposed to go back. – NullUserException Sep 05 '11 at 19:35
  • Well, I'm also not sure if I'm should use exception here, I had checked the exception handling in other languages and found that except VisualBASIC, most of the mainstream languages doesn't allow "going back after exception". so I'm asking the best practice to doing what I wanted: try to fix something when it goes wrong and re-do the instruction again. What I expected is not limited to exception handling mechanism. – LazNiko Sep 06 '11 at 00:17

4 Answers4

4
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();
ajreal
  • 46,720
  • 11
  • 89
  • 119
1
try{
    doTaskA(); 
} catch(MyException $e){
    fixMyException();
}

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

try{
    doTaskC(); 
} catch(MyException $e){
    fixMyException();
}
OZ_
  • 12,492
  • 7
  • 50
  • 68
1

How is that any different than doing

try {
    doTaskA(); 
} catch (MyException $e) {
    fixMyException();
}
try {
    doTaskB(); 
} catch (MyException $e) {
    fixMyException();
}
try {
    doTaskC(); 
} catch (MyException $e) {
    fixMyException();
}
Mike
  • 23,542
  • 14
  • 76
  • 87
  • thanks mike. but it looks quite bulky (and not DRY) even for just 3 tasks...i need to handle more than 10 tasks like this...I would like to wait and see if others can give a neater answer. – LazNiko Sep 01 '11 at 14:55
1

No it is not possible. You'd need to put each of doTask*() functions in it's own separate try-catch block.

Mchl
  • 61,444
  • 9
  • 118
  • 120