如何退出if语句并继续执行else


How to exit if statement and continue to else

这是一个很长的问题,但如果if块内部发生错误,php中是否有方法退出"if"语句并继续执行"else"语句?

示例

if ($condition == "good")
{
//do method one
//error occurs during method one, need to exit and continue to else 
}
else 
{
//do method two
}

当然,在第一个if中嵌套if是可能的,但这似乎很难。

TIA

try {
    //do method one
    //error occurs during method one, need to exit and continue to else 
    if ($condition != "good") {
        throw new Exception('foo');
    }
} catch (Exception $e) {
    //do method two
}

我只想使用一个函数,这样你就不会重复代码:

if ($condition == "good") {
    //do method one
    //error occurs during method one
    if($error == true) {
        elsefunction();
    }
} else {
    elsefunction();
}
function elsefunction() {
    //else code here
}

这可能吗?无论如何,你可以考虑将其更改为.

$error = "";
if ($condition == "good") {
 if (/*errorhappens*/) { $error = "somerror"; }
}
if (($condition != "good") || ($error != "") ) {
 //dostuff
}

您可以修改methodOne(),使其在成功时返回true,在错误时返回false

if($condition == "good" && methodOne()){
  // Both $condition == "good" and methodOne() returned true
}else{
  // Either $condition != "good" or methodOne() returned false
}

假设methodOne在出现错误时返回false:

if !($condition == "good" && methodOne())
{
//do method two
}

你真的需要这个吗?我想没有…但你可以破解。。

do{
   $repeat = false;
   if ($condition == "good")
   {
      //do method one
      $condition = "bad";
      $repeat = true;
    }    
    else 
    {
       //do method two
    }
}while( $ok ) ;

我建议如何分离。。。

我发现使用开关而不是if…else很方便:省略break语句会使开关陷入下一种情况:

switch ($condition) {
case 'good':
    try {
        // method to handle good case.
        break;
    }
    catch (Exception $e) {
        // method to handle exception
        // No break, so switch continues to default case.
    }
default:
    // 'else' method
    // got here if condition wasn't good, or good method failed.
}
if ($condition == "good") {
    try{
        method_1();
    }
    catch(Exception $e){
       method_2();
    }
} 
else {
    method_2();
}
function method_2(){
   //some statement
}