E
x
c
e
l
P
T
P

Basic Use of PHP Exceptions ?

December 15, 2015

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching “catch” block.

If an exception is not caught, a fatal error will be issued with an “Uncaught Exception” message.

Lets try to throw an exception without catching it:

<?php
//create function with an exception
function checkmyNum($num) {
  if($num>1) {
    throw new Exception(“Value must be 1 or below”);
  }
  return true;
}

//trigger exception
checkmyNum(2);
?>

The code above will get an error like this:

Fatal error: Uncaught exception ‘Exception’
with message ‘Value must be 1 or below’ in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkmyNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6
 

Try, throw and catch

To avoid the error from the example above, we need to create the proper code to handle an exception.

Proper exception code should include:

  1. Try – A function using an exception should be in a “try” block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”
  2. Throw – This is how you trigger an exception. Each “throw” must have at least one “catch”
  3. Catch – A “catch” block retrieves an exception and creates an object containing the exception information