在PHP中使用try-catch如何在没有抛出异常的情况下最终进入?

在PHP中使用try-catch如何在没有抛出异常的情况下最终进入?

问题描述:

About the following code, how can I go to finally without throw an Exception in PHP?

try {
  $db = DataSource::getConnection();
  if (some condition here is TRUE) { 
     // go to finally without throw an exception 
  }
  $stmt = $db->prepare($sql);
  $stmt->saveMyData();
} catch (Exception $e) {
  die($e->getMessage());
} finally {
  $db = null;
}

Please don't do this, but here's an option:

try {
    if (TRUE){
        goto ugh;
    }
    echo "
did not break";
    ugh:
} catch (Exception $e){
    echo "
did catch";
} finally {
    echo "
i'm so tired";
}

I strongly encourage against using a goto. I think it's just really easy for code to get sloppy & confusing if you're using goto.

I'd recommend:

try {
    if (TRUE){
        echo "
That's better";
    } else {
       echo "
did not break";
    }
} catch (Exception $e){
    echo "
did catch";
} finally {
    echo "
i'm so tired";
}

You just wrap the rest of the try into an else in order to skip it.


Another option could be to declare a finally function, call that, and return.

//I'm declaring as a variable, as to not clutter the declared methods
//If you had one method across scripts, naming it `function doFinally(){}` could work well
$doFinally = function(){};
try {
    if (TRUE){
        $doFinally();
        return;
    }
    echo "
did not break";
} catch (Exception $e){
    echo "
did catch";
} finally {
    $doFinally();
}

If you needed to continue the script, you could declare $doFinally something like:

$doFinally = function($reset=FALSE){
    static $count;
    if ($reset===TRUE){
        $count = 0;
        return;
    } else if ($count===NULL)$count = 0;
    else if ($count>0)return;
}

Then after the finally block, you could call $doFinally(TRUE) to reset it for the next try/catch