Categories
programming

PHP Exceptions

Example:

  1. exception is thrown
  2. following code is not executed
  3. PHP looks for catch block
  4. if catch block is not found, fatal error is issued with Uncaught Exception message

Solution:

  1. try – a function using an exception should be on a “try” block
  2. catch – a “catch” block retrieves an exception and creates an object containing the exception information
function x(){
  if(true) throw new Exception("error");
  return false;
}

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

You can create custom exception class that inheres properties from PHP’s exception class and add custom functions to it.

try{
  x();
} catch (Exception $e){
  throw new CustomException();
}

Leave a Reply

Your email address will not be published. Required fields are marked *