PHP Tutorial PHP Advanced PHP References

PHP - Exceptions



PHP has an exception model similar to that of other programming languages. An exception is an object that describes an error or unexpected behavior of a PHP script. Exceptions are thrown by many PHP functions and classes. User defined functions and classes can also throw exceptions. Exceptions are a good way to stop a function when it comes across data that it cannot use.

Throwing an Exception

The throw keyword is used to throw exceptions. When an exception is thrown, the code following it will not be executed. Note that, if an exception is not caught, a fatal error will occur with an "Uncaught Exception" message.

Consider the example below where the throw keyword is used to throw an exception.

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

echo divide(25, 0);
?>

The output of the above code will be similar to:

PHP Fatal error:  Uncaught Exception: Division by zero in Main.php:4
Stack trace:
#0 Main.php(9): divide()
#1 {main}
  thrown in Main.php on line 4

The try-catch blocks

To avoid the situation above, try-catch code blocks can be used. The try keyword is used to test a block of statements for error and catch keyword is used to define a block of statements which executes when error occurs and handles error. The syntax for using try-catch blocks are given below:

Syntax

try{
  statements;
} catch (Exception $e) {
  statements;
}

Consider the example below where try-catch code blocks are used to handle the exception.

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo divide(25, 0);
} catch(Exception $e) {
  echo "Division by zero is invalid.";
}
?>

In the example above, the type of exception is Exception and the variable name is $e. The output of the above code will be:

Division by zero is invalid.

The finally block

The finally keyword is used to define a block of statements which executes regardless of try-catch blocks result. It facilitates the program to close the file before proceeding further.

Syntax

try{
  statements;
} catch (Exception $e) {
  statements;
} finally {
  statements;
}

In the example below, finally block of code is used which is executed after try-catch blocks of code.

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo divide(25, 0);
} catch(Exception $e) {
  echo "Division by zero is invalid.\n";
} finally {
  echo "try-catch block finished.\n";
}
?>

The output of the above code will be:

Division by zero is invalid.
try-catch block finished.

The Exception Class

Exception is the base class for all user exceptions. An Exception object contains information about the error or unexpected behavior that the function encountered. The Exception object can be created using following syntax:

Syntax

public __construct(message, code, previous)

Parameters

message Optional. Specify the Exception message to throw.
code Optional. Specify the Exception code.
previous Optional. Specify the previous exception used for the exception chaining.

Methods

The Exception class provides the following methods:

MethodsDescription
getMessage()Gets the Exception message
getPrevious()Returns previous Throwable
getCode()Gets the Exception code
getFile()Gets the file in which the exception was created
getLine()Gets the line in which the exception was created
getTrace()Gets the stack trace
getTraceAsString()Gets the stack trace as a string
__toString()String representation of the exception

Consider the example below where Exception class methods are used.

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero", 3);
  }
  return $dividend / $divisor;
}

try {
  echo divide(25, 0);
} catch(Exception $e) {
  $code = $e->getCode();
  $message = $e->getMessage();
  $file = $e->getFile();
  $line = $e->getLine();
  echo "Exception thrown in $file on line $line: [Code $code]
  $message";
}
?>

The output of the above code will be:

Exception thrown in Main.php on line 4: [Code 3]
  Division by zero

5