w3resource

PHP exception handling: Handling specific exceptions


10. Specific Exception Handling Actions

Write a PHP program that uses a try-catch block to handle a specific exception and performs specific actions based on the exception type.

Sample Solution:

PHP Code :

<?php
class CustomException extends Exception {
    public function __construct($message, $code = 0, Throwable $previous = null) {
        parent::__construct($message, $code, $previous);
    }
    
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }
}

try {
    // Code that may throw a specific exception
    $number = "abc";
    
    if (!is_numeric($number)) {
        throw new CustomException("Invalid number.");
    }
    
    $result = 200 / $number;
    echo "Result: " . $result;
} catch (CustomException $e) {
    // Handle CustomException
    echo "CustomException: " . $e->getMessage();
    // Perform specific actions for CustomException
    // ...
} catch (Exception $e) {
    // Handle generic Exception
    echo "Exception: " . $e->getMessage();
}
?>

Sample Output:

CustomException: Invalid number

Explanation:

In the above exercise,

  • We have a try block that contains code that throws a specific exception. We check if the $number is numeric using is_numeric() and throw a CustomException if it's not.
  • The first catch block catches the CustomException specifically and handles it separately. It displays an appropriate error message using $e->getMessage() and can perform specific actions for the CustomException.
  • The second catch block catches a generic Exception if another type of exception occurs. It displays an appropriate error message using $e->getMessage().

Flowchart:

Flowchart: Handling specific exceptions

For more Practice: Solve these Related Problems:

  • Write a PHP script that throws a specific exception based on a given error code and catches it to perform a corresponding recovery action.
  • Write a PHP function that processes an input and throws different exceptions for distinct error conditions, then handles each using specific catch blocks.
  • Write a PHP program to simulate an operation where a specific exception is thrown and then a custom action is taken in the catch block before rethrowing.
  • Write a PHP script to implement a try-catch structure that distinguishes errors based on exception messages and executes alternative code paths accordingly.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: PHP exception handling with the finally block.

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.