In this tutorial, you shall learn how to define multiple catch blocks in a try-catch statement in PHP, with the help of example programs.

PHP – Multiple Catch Blocks

In PHP try catch statement, if the try block can throw more than one type of Exception, we can have more than one catch block. Just add required catch blocks to the try-catch.

Syntax

The syntax of try catch statement with multiple catch blocks is

try {
    //code
} catch (Exception1 $e) {
    //code
} catch (Exception2 $e) {
    //code
} catch (Exception3 $e) {
    //code
}

Replace Exception1, Exception2, Exception3, .., with the type of exceptions that the try block can throw.

ADVERTISEMENT

Example

In the following example, we have some code in try block that throws user defined Exceptions: NumberTooLargeException or NumberTooSmallException based on the value of $x. We write multiple catch blocks to catch these different exceptions.

PHP Program

<?php
  class NumberTooLargeException extends Exception { }
  class NumberTooSmallException extends Exception { }

  try {
    $x = 152;

    if ($x < 10) {
      throw new NumberTooSmallException("The given number is too small.");
    } elseif ($x > 90) {
      throw new NumberTooLargeException("The given number is too large.");
    } else {
      echo "x is within the desired range.";
    }
  } catch (NumberTooLargeException $e) {
    //handle exception
    echo $e->getMessage();
  } catch (NumberTooSmallException $e) {
    //handle exception
    echo $e->getMessage();
  }
?>

Output

If you try with $x = 5, the code in try block throws NumberTooSmallException, and the respective catch block handles the exception.

Conclusion

In this PHP Tutorial, we learned how to write multiple catch blocks in a try-catch statement.