只有在没有抛出异常的情况下,才能在try块之外执行代码的最简洁方法

This question is about the best way to execute code outside of try block only if no exception is thrown.

try {
    //experiment
    //can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
    //contain the blast
} finally {
    //cleanup
    //this is not the answer since it executes even if an exception occured
    //finally will be available in php 5.5
} else {
    //code to be executed only if no exception was thrown
    //but no try ... else block exists in php
}

This is method suggested by @webbiedave in response to the question php try .. else. I find it unsatisfactory because of the use of the extra $caught variable.

$caught = false;

try {
    // something
} catch (Exception $e) {
    $caught = true;
}

if (!$caught) {

}

So what is a better (or the best) way to accomplish this without the need for an extra variable?

One possibility is to put the try block in a method, and return false if an exception is cought.

function myFunction() {
    try {
        // Code  that throws an exception
    } catch(Exception $e) {
        return false;
    }
    return true;
}

Have your catch block exit the function or (re)throw/throw an exception. You can filter your exceptions as well. So if your other code also throws an exception you can catch that and (re)throw it. Remember that:

  1. Execution continues if no exception is caught.
  2. If an exception happens and is caught and not (re)throw or a new one throw.
  3. You don't exit your function from the catch block.
  4. It's always a good idea to (re)throw any exception that you don't handle.
  5. We should always be explicit in our exception handling. Meaning if you catch exceptions check the error that we can handle anything else should be (re)throw(n)

The way I would handle your situation would be to (re)throw the exception from the second statement.

try {
    $this->throwExceptionA();
    $this->throwExceptionB();

} catch (Exception $e) {
    if($e->getMessage() == "ExceptionA Message") {
        //Do handle code

    } elseif($e->getMessage() == "ExceptionB Message") {
        //Do other clean-up
        throw $e;

    } else {
        //We should always do this or we will create bugs that elude us because
        //we are catching exception that we are not handling
        throw $e;
    }
}