Differentiate between exception and error in PHP


Let's discuss the differences between errors and exceptions.

  • Recovering from Error is not possible. The only solution to errors is to terminate the execution. Whereas we can recover from Exception by using either try-catch blocks or throwing an exception back to the caller.
  • You will not be able to handle the Errors using try-catch blocks. Even if you handle them using try-catch blocks, your application will not recover if they happen. On the other hand, Exceptions can be handled using try-catch blocks and can make program flow normally if they happen.
  • Exceptions are related to the application whereas Errors are related to the environment in which application is running.

Example

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

Explanation

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.

Example

<?php
   $foo = [bar];
   echo $foo;
 ?>

Explanation

Program execution will stop with PHP Notice: Array to string conversion.

Updated on: 29-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements