PHP Nested Exception

In PHP, nested exceptions allow you to handle multiple types of errors at different levels. You can nest try-catch blocks to any desired depth, with exceptions being handled in reverse order − innermost exceptions are processed first.

Syntax

The basic structure of nested exception handling ?

try {
    // Outer try block
    try {
        // Inner try block
        // Code that may throw exceptions
    } catch (SpecificException $e) {
        // Handle inner exception
    }
    // More outer code
} catch (AnotherException $e) {
    // Handle outer exception
}

Example

In this example, the inner try block checks if variables are non-numeric and throws a custom exception. The outer try block handles division by zero errors ?

<?php
class myException extends Exception {
    function message() {
        return "error : " . $this->getMessage() . " in line no " . $this->getLine();
    }
}

$x = 10;
$y = 0;

try {
    try {
        if (is_numeric($x) == FALSE || is_numeric($y) == FALSE)
            throw new myException("Non numeric data");
    } catch (myException $m) {
        echo $m->message();
        return;
    }
    
    if ($y == 0)
        throw new DivisionByZeroError("Division by 0");
    
    echo $x / $y;
} catch (DivisionByZeroError $e) {
    echo $e->getMessage() . " in line no " . $e->getLine();
}
?>

The output when dividing by zero ?

Division by 0 in line no 19

If you change any variable to a non-numeric value like $x = "abc", the output will be ?

error : Non numeric data in line no 13

When both variables are valid numbers and the denominator is not zero, their division is calculated and displayed.

How It Works

The exception handling flow follows these steps ?

  • Inner try block validates numeric data first
  • If validation fails, the custom exception is caught immediately
  • If validation passes, the outer try block checks for division by zero
  • Each catch block handles its specific exception type

Conclusion

Nested exceptions provide granular error handling by allowing different exception types to be caught at appropriate levels. This approach helps create more robust applications with specific error responses.

Updated on: 2026-03-15T09:10:47+05:30

696 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements