从try/catch块中断

Elf*_*lfy 11 php exception try-catch

这可能在PHP?

try {

  $obj = new Clas();

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

  // do other stuff here

} catch(Exception $e) {

}
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*att 15

当然有了转到!

try {

  $obj = new Clas();

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

  // do other stuff here

} catch(Exception $e) {

}
break_free_of_try:
Run Code Online (Sandbox Code Playgroud)

  • Christos,你似乎在错误的假设下操作,即我的代码还不是意大利面条。 (4认同)
  • 这个答案让我感到既恐惧又强大。 (2认同)
  • 功能强大。“ goto”没错-这是一个古老的神话。我们中的许多程序员都在等待业界意识到Dijkstra辩论已经结束,如果您知道自己在做什么,直接跳转就没有错。 (2认同)

vik*_*ter 11

好吧,没有理由这样做,但你可以在你的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";
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我也遇到过这种情况,并且像你一样,不想要无数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";
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的主要代码中,我称之为;

throw new ValidationEx('You maniac!');
Run Code Online (Sandbox Code Playgroud)

然后在Try语句结束时我有

        catch(ValidationEx $e) { echo $e->getMessage(); }
        catch(Exception $e){ echo $e->getMessage(); }
Run Code Online (Sandbox Code Playgroud)

对于评论和批评感到高兴,我们都在这里学习!


小智 4

try
{
    $object = new Something();
    if ($object->value)
    {
        // do stuff
    }
    else
    {
        // do other stuff
    }
}
catch (Exception $e)
{
     // handle exceptions
}
Run Code Online (Sandbox Code Playgroud)