PHP: exceptions vs errors?

Exceptions are thrown – they are intended to be caught. Errors are generally unrecoverable. Lets say for instance – you have a block of code that will insert a row into a database. It is possible that this call fails (duplicate ID) – you will want to have a “Error” which in this case is an “Exception”. When you are inserting these rows, you can do something like this

try {
  $row->insert();
  $inserted = true;
} catch (Exception $e) {
  echo "There was an error inserting the row - ".$e->getMessage();
  $inserted = false;
}

echo "Some more stuff";

Program execution will continue – because you ‘caught’ the exception. An exception will be treated as an error unless it is caught. It will allow you to continue program execution after it fails as well.

Leave a Comment