考虑这两个例子

<?php
function throw_exception() {
    // Arbitrary code here
    throw new Exception('Hello, Joe!');
}

function some_code() {
    // Arbitrary code here
}

try {
    throw_exception();
} catch (Exception $e) {
    echo $e->getMessage();
}

some_code();

// More arbitrary code
?>


<?php
function throw_exception() {
    // Arbitrary code here
    throw new Exception('Hello, Joe!');
}

function some_code() {
    // Arbitrary code here
}

try {
    throw_exception();
} catch (Exception $e) {
    echo $e->getMessage();
} finally {
    some_code();
}

// More arbitrary code
?>

有什么不同?是否存在第一个示例不执行some_code(),而第二个示例执行的情况?我是否完全忘记了要点?

最佳答案

如果捕获到Exception(任何异常),则这两个代码示例是等效的。但是,如果仅在类块中处理某些特定的异常类型,并且发生另一种异常,则只有在具有some_code();块的情况下才会执行finally

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
}

some_code(); // Will not execute if throw_exception throws an ExceptionTypeB

但:
try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
} finally {
    some_code(); // Will be execute even if throw_exception throws an ExceptionTypeB
}

08-26 08:08