WikiGalaxy

Personalize

PHP Exception Handling

Understanding Exceptions

Exceptions are used to change the normal flow of a script if a specified error condition occurs. In PHP, exceptions are thrown using the throw statement and caught using a try...catch block.


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

try {
  echo divide(10, 0);
} catch (Exception $e) {
  echo "Caught exception: " . $e->getMessage();
}
?>
    

Console Output:

Caught exception: Division by zero

Custom Exception Classes

Creating Custom Exceptions

You can create your own exception classes in PHP by extending the base Exception class. This allows for more specific error handling.


<?php
class CustomException extends Exception {
  public function errorMessage() {
    return "Error on line " . $this->getLine() . " in " . $this->getFile()
    . ": <b>" . $this->getMessage() . "</b> is not a valid E-Mail address";
  }
}

$email = "someone@example...com";

try {
  if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    throw new CustomException($email);
  }
} catch (CustomException $e) {
  echo $e->errorMessage();
}
?>
    

Console Output:

Error on line 10 in /path/to/script.php: <b>someone@example...com</b> is not a valid E-Mail address

Multiple Catch Blocks

Handling Different Exceptions

PHP allows multiple catch blocks to handle different types of exceptions separately.


<?php
class DivideByZeroException extends Exception {}
class InvalidArgumentException extends Exception {}

function divide($a, $b) {
  if ($b == 0) {
    throw new DivideByZeroException("Cannot divide by zero");
  }
  if (!is_numeric($a) || !is_numeric($b)) {
    throw new InvalidArgumentException("Both arguments must be numbers");
  }
  return $a / $b;
}

try {
  echo divide(10, 0);
} catch (DivideByZeroException $e) {
  echo "Caught DivideByZeroException: " . $e->getMessage();
} catch (InvalidArgumentException $e) {
  echo "Caught InvalidArgumentException: " . $e->getMessage();
}
?>
    

Console Output:

Caught DivideByZeroException: Cannot divide by zero

Finally Block

Executing Code Regardless of Exception

The finally block contains code that should run regardless of whether an exception was thrown or not.


<?php
function testFinally() {
  try {
    echo "Trying...\n";
    throw new Exception("An error occurred");
  } catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage() . "\n";
  } finally {
    echo "This is the finally block.\n";
  }
}

testFinally();
?>
    

Console Output:

Trying... Caught exception: An error occurred This is the finally block.

Re-throwing Exceptions

Propagating Exceptions

You can re-throw an exception within a catch block by using the throw statement again.


<?php
function checkNumber($number) {
  if($number > 1) {
    throw new Exception("Value must be 1 or below");
  }
  return true;
}

try {
  checkNumber(2);
} catch (Exception $e) {
  echo "Caught exception: " . $e->getMessage() . "\n";
  throw $e; // Re-throwing exception
}
?>
    

Console Output:

Caught exception: Value must be 1 or below

Using Set Exception Handler

Global Exception Handling

PHP allows you to set a global exception handler function using set_exception_handler(). This function will handle uncaught exceptions.


<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>
    

Console Output:

Uncaught exception: Uncaught Exception

Error Handling with Exceptions

Using Exceptions for Error Handling

In PHP, you can convert errors to exceptions using the ErrorException class and set_error_handler().


<?php
function error_handler($errno, $errstr, $errfile, $errline) {
  throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}

set_error_handler("error_handler");

try {
  echo $undefined_variable;
} catch (ErrorException $e) {
  echo "Caught error: " . $e->getMessage();
}
?>
    

Console Output:

Caught error: Undefined variable: undefined_variable

Try-Catch in Loops

Handling Exceptions in Loops

You can handle exceptions within loops by placing the try-catch block inside the loop.


<?php
$numbers = [2, 0, 4];

foreach ($numbers as $number) {
  try {
    echo 10 / $number . "\n";
  } catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage() . "\n";
  }
}
?>
    

Console Output:

5 Caught exception: Division by zero 2.5

Exception Chaining

Chaining Exceptions

Exception chaining is a technique where a caught exception is wrapped in a new exception and re-thrown.


<?php
function firstFunction() {
  try {
    throw new Exception("Exception in firstFunction");
  } catch (Exception $e) {
    throw new Exception("Exception in secondFunction", 0, $e);
  }
}

try {
  firstFunction();
} catch (Exception $e) {
  echo "Caught exception: " . $e->getMessage() . "\n";
  echo "Previous exception: " . $e->getPrevious()->getMessage();
}
?>
    

Console Output:

Caught exception: Exception in secondFunction Previous exception: Exception in firstFunction

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025