php – GOTO和THROW之间的区别?

最近有很多人指责我只提一个字 – “goto”.
这让我很奇怪,为什么它被认为是一个令人讨厌的词.
我知道之前关于这个主题的几个讨论,但它并没有说服我 – s ome of the answers just says “it’s bad” not even trying to explain和一些带来 reasons,irrelevant for scripting languages like PHP,IMO.

无论如何,我要问一个非常特别的问题:
让我们比较goto和throw语句.
在我看来,两者都做同样的事情:避免基于某些条件执行某些代码.
如果是这样 – 抛出与goto有相同的缺点吗? (如果有的话)?
如果不是 – 那就是惠特.

任何经验丰富的人,谁能说出以下两个代码片段的代码结构之间的基本概念差异?
关于这些非常的代码片段,不是“在理论上”或“一般”或“这里是一个不错的XKCD漫画!”.
为什么第一个被认为是辉煌的而后一个被认为是最致命的罪?

#$a=1;
#$b=2;

/* SNIPPET #1 */

try {
    if (!isset($a)) {
      throw new Exception('$a is not set');
    }
    if (!isset($b)) {
      throw new Exception('$b is not set');
    }
    echo '$a + $b = '.($a + $b)."<br>\n";
} catch (Exception $e) {
    echo 'Caught exception: ',$e->getMessage(),"<br>\n";
}

/* SNIPPET #2 */

if (!isset($a)) { 
  $message = '$a is not set';
  goto end;
}
if (!isset($b)) {
  $message = '$b is not set';
  goto end;
}
echo '$a + $b = '.($a + $b)."<br>\n";

end:
if (!empty($message)) {
  echo 'Caught exception: ',$message,"<br>\n";
}

请注意,我知道投掷在制作意大利面条时更加强大和灵活.它对我来说并不是主要的区别.这是使用问题,而不是概念.

编辑
很多人都告诉我,第一个例子应该是新用的.
原因:异常应仅用于处理错误,而不是用于实现业务逻辑.
它看起来很明智.

因此,停止无用的代码执行的唯一方法是转到(更不用说一些替代品,例如while,return等,这些是同样但更难实现的)?

由于没有人提出这个问题的答案,OP被认为是可以接受的,所以我会戴上帽子.

…the fundamental,conceptual difference between code structures
of the two following code snippets?

您提供的两个代码段之间没有任何概念上的差异.在这两种情况下都会测试一个条件,如果满足,则会向程序的另一部分抛出一条消息以进行处理.

Why the first one considered to be brilliant and latter one considered
to be deadliest of sins?

谢谢Col. Shrapnel打开以下咆哮的大门.

<咆哮>

每个编程结构都有可能被滥用.对goto的教条迫害让我想起了类似的对PHP的抨击. PHP导致错误的编程实践.相比之下:Goto导致意大利面条代码.

简单地说:goto是“邪恶的”,因为Edsger Dijkstra这样说并且Niklaus Wirth给了他批准的印章. ;-p

< /咆哮>

为了您的阅读享受:http://en.wikipedia.org/wiki/Goto

Probably the most famous criticism of GOTO is a 1968 letter by Edsger
Dijkstra called Go To Statement Considered Harmful. In that letter
Dijkstra argued that unrestricted GOTO statements should be abolished
from higher-level languages because they complicated the task of
analyzing and verifying the correctness of programs (particularly
those involving loops). An alternative viewpoint is presented in
Donald knuth’s Structured Programming with go to Statements which
analyzes many common programming tasks and finds that in some of them
GOTO is the optimal language construct to use.

它继续说,

Some programmers,such as Linux Kernel designer and coder Linus
Torvalds or software engineer and book author Steve McConnell also
object to Dijkstra’s point of view,stating that GOTOs can be a useful
language feature,improving program speed,size and code clearness,
but only when used in a sensible way by a comparably sensible
programmer.

也就是说,自从Commodore BASIC以来,我个人还没有找到GOTO的实际用途,但这既不是在这里也不是在那里.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...