Skip to main content

PHP Exceptions

By SamK
0
0 recommends
Topic(s)

An exception is an object that signifies an error or an unexpected condition in a PHP script.

Various PHP functions and classes are capable of throwing exceptions.

Using exceptions provides an efficient way to stop the execution of a function when it encounters data it cannot handle or process.

Throwing an Exception

The throw statement allows a user-defined function or method to throw an exception. Once an exception is thrown, any code that follows it will not be executed.

If the exception is not caught, a fatal error occurs, and an "Uncaught Exception" message will be displayed.

Example: Throwing an exception without handling it.

<?php
function multiply($factor1, $factor2) {
  if($factor2 == 0) {
    throw new Exception("Multiplication by zero is not allowed");
  }
  return $factor1 * $factor2;
}

echo multiply(5, 0);
?>

The output will appear as follows:

Uncaught Exception: Multiplication by zero is not allowed in ...

The try...catch Statement

To avoid the error shown in the previous example, we can use the try...catch statement to handle exceptions and allow the process to proceed without interruption.

Syntax:

try {
   // Code that might trigger an exception
} catch (Exception $exception) {
   // Code to execute if an exception is caught
}

Example: Display a message when an exception is thrown.

<?php
function multiply($factor1, $factor2) {
  if ($factor2 == 0) {
    throw new Exception("Multiplication by zero is not allowed");
  }
  return $factor1 * $factor2;
}

try {
  echo multiply(5, 0);  // Testing with factor2 as 0
} catch(Exception $e) {
  echo "Error: Unable to perform multiplication.";
}

/*
Output:
Error: Unable to perform multiplication.
*/
?>

The try-catch block catches the exception, and instead of showing the specific exception message, it displays a generic error message: "Error: Unable to perform multiplication.".

The try...catch...finally Statement

The try...catch...finally statement is used to handle exceptions. The code inside the finally block will always execute, regardless of whether an exception was thrown or caught. When a finally block is included, the catch block becomes optional.

Syntax

try {
    // Code that could potentially throw an exception
} catch (Exception $exception) {
    // Code to execute if an exception is caught
} finally {
    // Code that will always execute, regardless of exception handling
}

Example: Display a message when an exception is thrown, and then indicate that the process has concluded.

<?php
function subtract($minuend, $subtrahend) {
  if ($subtrahend == 0) {
    throw new Exception("Subtraction by zero is not allowed");
  }
  return $minuend - $subtrahend;
}

try {
  echo subtract(5, 0);  // Testing with subtrahend as 0
} catch(Exception $e) {
  echo "Error: Unable to perform subtraction. ";
} finally {
  echo "<br>Process complete.";
}

/*
Output:
Error: Unable to perform subtraction. 
Process complete.
*/
?>

The Exception Object

The Exception object provides details about the error or unexpected behavior that occurred within the function.

Syntax

new Exception($message, $code, $previous)

Parameter Values

  • message - Optional (string): Provides an explanation for why the exception was thrown.
  • code - Optional (string): Used to uniquely identify this exception among other exceptions of the same type.
  • previous - Optional (string): If this exception was thrown while handling another exception, it is recommended to pass the previous exception as the parameter.

Methods

When handling an exception, the following methods can be used to retrieve details about the exception:

getMessage(): Returns a string that explains why the exception was thrown.
getPrevious(): If this exception was caused by another, it returns the previous exception; otherwise, it returns null.
getCode(): Retrieves the code associated with the exception.
getFile(): Returns the full path of the file where the exception occurred.
getLine(): Provides the line number in the code where the exception was raised.

Example: Show information about the exception that was thrown.

<?php
function subtract($minuend, $subtrahend) {
  if ($subtrahend == 0) {
    throw new Exception("Subtraction by zero is not allowed", 2);
  }
  return $minuend - $subtrahend;
}

try {
  echo subtract(5, 0);  // Testing with subtrahend as 0
} catch(Exception $ex) {
  $code = $ex->getCode();
  $message = $ex->getMessage();
  $file = $ex->getFile();
  $line = $ex->getLine();
  echo "Exception thrown in $file on line $line: [Code $code] $message";
}

/*
Output:
Exception thrown in /path/to/your/script.php on line 9: [Code 2] Subtraction by zero is not allowed
*/
?>

Questions & Answers