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?

Edited by AngelicOne: n/a

6 Years
Discussion Span
Last Post by pritaeas

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


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 {
catch(Exception $e) {
  echo $e->getMessage();

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

Edited by pritaeas: n/a

Votes + Comments
Good answer. @pritaeas, Zero13
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.