mar*_*son 20 php finally try-catch-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
?>
Run Code Online (Sandbox Code Playgroud)
和
<?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
?>
Run Code Online (Sandbox Code Playgroud)
有什么不同?是否有第一个例子不会执行的情况some_code()
,但第二个例子会不会执行?我完全忽略了这一点吗?
Sim*_*mon 40
如果您捕获Exception(任何异常),则两个代码示例是等效的.但是如果你只在类块中处理某个特定的异常类型并发生另一种异常,那么some_code();
只有在你有一个finally
块时才会执行.
try {
throw_exception();
} catch (ExceptionTypeA $e) {
echo $e->getMessage();
}
some_code(); // Will not execute if throw_exception throws an ExceptionTypeB
Run Code Online (Sandbox Code Playgroud)
但:
try {
throw_exception();
} catch (ExceptionTypeA $e) {
echo $e->getMessage();
} finally {
some_code(); // Will be execute even if throw_exception throws an ExceptionTypeB
}
Run Code Online (Sandbox Code Playgroud)