本文介绍了PHP中的"finally"关键字是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这两个例子

<?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(),而第二个示例执行的情况?我是否完全忘记了要点?

What's the difference? Is there a situation where the first example wouldn't execute some_code(), but the second would? Am I missing the point entirely?

推荐答案

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

If you catch Exception (any exception) the two code samples are equivalent. But if you only handle some specific exception type in your class block and another kind of exception occurs, then some_code(); will only be executed if you have a finally block.

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
}

这篇关于PHP中的"finally"关键字是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:38
查看更多