Exception Handling with PHP


What is Exception

Exception is an error condition which change the normal flow of code execution. Exceptions are catchable. That means, we can catch and try to recover or continue with the execution of the program.

‘errors’ vs ‘exceptions’ : Generally errors occur at the language level (ie, the syntax is wrong, missing parenthesis etc)

Exceptions in PHP

Exceptions were introduced in PHP 5. It is used in an object oriented way. The exception model of PHP is very similar to exception model of other programming languages.

Exceptions can be thrown and caught.

one basic example,

  try {
    throw new Exception('An Exception');
  } catch (Exception $e) {
    echo $e->getMessage();
  }
  //output : An Exception

Example,

function inverse($number) {
  if ($number==0) {
      throw new Exception('Division by zero.');
  }

  return 1/$number;
}

try {
    $random_number = rand(0,5);
    $result = inverse($random_number);
    // ONLY echo when no exception is thrown
    echo $result;
} catch (Exception $e) {
    //ONLY echo if there is an exception
    echo "Exception Message :".$e->getMessage();
} finally {
    // always echo
    echo "I am always there";
}

Note : Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException. - php.net

Comments

comments powered by Disqus