从尝试/捕获块中分离出来

2022-08-30 22:43:31

这在 PHP 中可能吗?

try {

  $obj = new Clas();

  if ($obj->foo) {
    // how to exit from this try block?
  }

  // do other stuff here

} catch(Exception $e) {

}

我知道我可以把其他东西放在中间,但这会增加更大的代码块上的缩进,我不喜欢它:P{}


答案 1

当然是去哪儿的!

try {

  $obj = new Clas();

  if ($obj->foo) {
    goto break_free_of_try;
  }

  // do other stuff here

} catch(Exception $e) {

}
break_free_of_try:

答案 2

好吧,没有理由这样做,但是您可以在块中强制执行异常,停止执行函数。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";
}

推荐