Many people accused me recently for just mentioning a single word - "goto".
It makes me wonder, why it is considered such a nasty word.
I am aware of several previous discussions on the topic, but it doesn't convince me - some of the answers just says "it's bad" not even trying to explain and some bring reasons, irrelevant for scripting languages like PHP, IMO.
Anyway, I am going to ask a very particular question:
Let's compare goto
and throw
statements.
Both, in my opinion, do the same thing: avoiding execution of some portion of code based on some condition.
If so - do throw
have same disadvantages as goto? (if any)?
If not - whit is the difference then.
Anyone experienced enough, who can tell the fundamental, conceptual difference between code structures of the two following code snippets?
Regarding these very code snippets, not "in theory" or "in general" or "here is a nice XKCD comic!".
Why the first one considered to be brilliant and latter one considered to be deadliest of sins?
#$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";
}
Note that I am aware of the fact that throw is more powerful and flexible in making spaghetti. It does not make the principal difference for me. It is matter of use, not concept.
EDIT
I've been told by many people that first example should be newer used.
Reason: Exceptions should be used to handle errors only, not to implement business logic.
It looks sensible.
Therefore, the only way left to stop useless code execution is goto (not to mention some substitutes, such as while, return etc, which are the same matter but harder to implement)?