[英]Break from try/catch block
這在PHP中可行嗎?
try {
$obj = new Clas();
if ($obj->foo) {
// how to exit from this try block?
}
// do other stuff here
} catch(Exception $e) {
}
我知道我可以在{}
之間放置其他內容,但這會使縮進更大的代碼塊,而我不喜歡:P
當然有了goto !
try {
$obj = new Clas();
if ($obj->foo) {
goto break_free_of_try;
}
// do other stuff here
} catch(Exception $e) {
}
break_free_of_try:
嗯,沒有理由,但是您可以在try
塊中強制執行異常,從而停止執行函數,這很有趣。
try {
if ($you_dont_like_something){
throw new Exception();
//No code will be executed after the exception has been thrown.
}
} catch (Exception $e){
echo "Something went wrong";
}
我也面臨這種情況,就像您一樣,我不希望有無數的if / else if / else if / else語句,因為這會使代碼的可讀性降低。
我最終用自己的擴展了Exception類。 下面的示例類用於驗證問題,該問題在觸發時將產生不太嚴重的“日志通知”
class ValidationEx extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
在我的主要代碼中,我稱它為:
throw new ValidationEx('You maniac!');
然后在Try語句的結尾,我有
catch(ValidationEx $e) { echo $e->getMessage(); }
catch(Exception $e){ echo $e->getMessage(); }
很高興提出意見和批評,我們都在這里學習!
你不能只是這樣嗎?
try{
$obj = new Clas();
if(!$obj->foo){
// do other stuff here
}
}catch(Exception $e){
}
try
{
$object = new Something();
if ($object->value)
{
// do stuff
}
else
{
// do other stuff
}
}
catch (Exception $e)
{
// handle exceptions
}
在php 5.3+中,關於使用帶有try catch塊的異常的好處是,您可以創建自己的異常並按需要處理它們的方式和時間。 請參閱: 擴展異常
class AcceptedException extends \Exception
{
//...
}
然后,您可以捕獲特定的異常,或在catch \\Exception
塊中使用if ($e instanceof AcceptedException)
確定要如何處理異常。
try {
$obj = (object) array('foo' => 'bar');
if ($obj->foo) {
throw new \AcceptedException;
}
} catch (\AcceptedException $e) {
var_dump('I was accepted');
} catch (\Exception $e) {
if ($e instanceof \InvalidArgumentException) {
throw $e; //don't handle the exception
}
}
與許多替代解決方案相比,這使您的代碼更具可讀性,更易於排除故障。
我個人喜歡使用a退出try / catch語句
throw new MyException("optional message", MyException::ERROR_SUCCESS);
我顯然是通過使用以下方法捕獲的:
switch($e->getCode()) {
/** other cases make sense here */
case MyException::ERROR_SQL:
logThis("A SQL error occurred. Details: " . $e->getMessage());
break;
case MyException::ERROR_SUCCESS:
logThis("Completed with success. Details: " . $e->getMessage());
break;
case MyException::ERROR_UNDEFINED:
default:
logThis("Undefined error. Details: " . $e->getMessage());
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.