I know it's a good way to catch an exception but why not just make it into a simple if..else statement and run a block of codes then used die to stop the code following it from executing or echo to enable the scripts following it from executing. What's the difference?

Recommended Answers

All 5 Replies

die() just stops execution. Throw is a way to notify the caller that an error has occured. The caller can then handle the problem.

Die could notify the caller, right? die("message here");

From the manual: "Output a message and terminate the current script". Note the word terminate. With caller I mean, the function that calls your function, not the user who sees the message.

This is a bit of a late reply but when does this throw new exception best use?

That will be your choice. You can throw an exception when a function you write fails, or you could do it by using a return value. It all depends on how you want to write your own code. For example:

function mysqlConnect() {
  if (! mysql_connect(...))
    return false;
}

function mysqlConnectEx() {
  if (! mysql_connect(...))
    throw new Exception('Could not connect.');
}

When the first one fails, the function returns false indicating you have no connection and you can respond to that in an if.

The second function raises an exception which you trap using a try .. catch block.

if (! mysqlConnect())
  echo 'Connection problem';

try {
  mysqlConnectEx();
}
catch(Exception $e) {
  echo $e->getMessage();
}

Advantage of exception is that you can create your own, which can have additional processing/logging/whatever.

commented: Good answer. @pritaeas, Zero13 +8
commented: thanks +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.