w3resource

PHP Exception Handling: Multiple catch blocks


7. Multiple Catch Blocks Implementation

Write a PHP program that implements multiple catch blocks to handle different types of exceptions.

Sample Solution:

PHP Code :

<?php
try {
    // Code that may throw different types of exceptions
    $number = "abc";
    
    if (!is_numeric($number)) {
        throw new InvalidArgumentException("Invalid number.");
    }
    
    $result = 100 / $number;
    echo "Result: " . $result;
} catch (InvalidArgumentException $e) {
    // Handle InvalidArgumentException
    echo "InvalidArgumentException: " . $e->getMessage();
} catch (DivisionByZeroError $e) {
    // Handle DivisionByZeroError
    echo "DivisionByZeroError: " . $e->getMessage();
} catch (Throwable $e) {
    // Handle generic Throwable (catches any other type of exception)
    echo "An error occurred: " . $e->getMessage();
}
?>

Sample Output:

InvalidArgumentException: Invalid number.

Explanation:

In the above exercise,

We have a try block that contains code that throws different types of exceptions. We first check if the $number is numeric using is_numeric() function and throw an InvalidArgumentException if it's not.

Then, we attempt a division operation with $number to trigger a DivisionByZeroError if the number is zero.

The catch blocks are defined to handle specific exception types.

  • The first catch block catches InvalidArgumentException and displays an appropriate error message.
  • The second catch block catches DivisionByZeroError and handles it accordingly.
  • The third catch block catches Throwable, which is the base class for all exceptions, and handles any other type of exception that may occur.

Flowchart:

Flowchart: Multiple catch blocks

For more Practice: Solve these Related Problems:

  • Write a PHP script that distinguishes between different exception types using multiple catch blocks to provide tailored error messages.
  • Write a PHP function that throws either a standard exception or a custom exception based on input parameters, and handle each with separate catch blocks.
  • Write a PHP program that demonstrates nested try-catch blocks, catching specific exceptions at different levels.
  • Write a PHP script to implement multiple catch clauses, where one catch block rethrows an exception to be handled by an outer catch block.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Handling empty string exception.
Next: Exception handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.