web*_*ave 48
PHP没有try/catch/else.但是,您可以在catch块中设置一个可用于确定它是否已运行的变量:
$caught = false;
try {
// something
} catch (Exception $e) {
$caught = true;
}
if (!$caught) {
}
Run Code Online (Sandbox Code Playgroud)
我认为"else"子句有点限制,除非你不关心那里抛出的任何异常(或者你想要冒泡那些异常)......从我对Python的理解,它基本上相当于:
try {
//...Do Some Stuff Here
try {
// Else block code here
} catch (Exception $e) {
$e->elseBlock = true;
throw $e;
}
} catch (Exception $e) {
if (isset($e->elseBlock) && $e->elseBlock) {
throw $e;
}
// catch block code here
}
Run Code Online (Sandbox Code Playgroud)
所以它有点冗长(因为你需要重新抛出异常),但它也会像使用else子句一样冒泡堆栈...
编辑或者,更清洁的版本(仅限5.3)
class ElseException extends Exception();
try {
//...Do Some Stuff Here
try {
// Else block code here
} catch (Exception $e) {
throw new ElseException('Else Clasuse Exception', 0, $e);
}
} catch (ElseException $e) {
throw $e->getPrevious();
} catch (Exception $e) {
// catch block code here
}
Run Code Online (Sandbox Code Playgroud)
编辑2
重新阅读你的问题,我认为你可能用"else"块过度复杂化了......如果你只是打印(不太可能抛出异常),你真的不需要一个else块:
try {
// Do Some stuff
print "Success";
} catch (Exception $e) {
//Handle error here
print "Error";
}
Run Code Online (Sandbox Code Playgroud)
该代码将只打印要么 Success
或Error
...从来都(因为如果print
函数抛出异常,也不会被实际打印...但我不认为print
可以抛出异常......).
Mva*_*est -2
您可以使用try { } catch () { }
和throw
。请参阅http://php.net/manual/en/language.exceptions.php
try {
$a = 13/0; // should throw exception
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Run Code Online (Sandbox Code Playgroud)
或手动:
try {
throw new Exception("I don't want to be tried!");
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14348 次 |
最近记录: |