考虑这两个例子
<?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(任何异常),则两个代码示例是等效的。但是如果你只在你的类 block 中处理一些特定的异常类型并且发生了另一种异常,那么 some_code();
只有在你有一个 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 - PHP 中的 `finally` 关键字是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17292959/