w3resource

PHP Custom Exception Class: Creating and throwing custom exceptions


2. Custom Exception Class

Write a PHP program that creates a custom exception class in PHP and throw an instance of it within a try block.

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 custom exception
    $roll_no = -15;
    
    if ($roll_no < 0) {
        throw new CustomException("Roll number cannot be negative.");
    }
    
    echo "Roll number: " . $age;
  } catch (CustomException $e) {
    // Custom exception handling code
    echo "An error occurred: " . $e->getMessage();
}
?>

Sample Output:

An error occurred: Roll number cannot be negative.

Explanation:

In the above exercise,

  • In this example, we create a custom exception class CustomException that extends the base Exception class. The custom exception class has a constructor that calls the parent constructor and overrides the __toString() method to provide a custom string representation of the exception.
  • Inside the try block, we have a check for a negative age. If the condition is true, we throw an instance of the CustomException class with the message "Age cannot be negative."
  • The catch block specifically catches instances of the CustomException class, allowing us to handle the custom exception separately. In this case, we simply display the error message using $e-<getMessage().

Flowchart:

Flowchart: Creating and throwing custom exceptions

For more Practice: Solve these Related Problems:

  • Write a PHP script that defines a custom exception class with additional properties and throws an instance of that class on a specific error condition.
  • Write a PHP function that validates input and throws your custom exception when the input does not meet required criteria.
  • Write a PHP program that catches your custom exception and accesses its custom properties to output detailed error information.
  • Write a PHP script to implement a custom exception hierarchy with at least two custom exception classes and throw them based on different error conditions.

Go to:


PREV : Basic Try-Catch Usage.
NEXT : Division with Exception Handling.

PHP Code Editor:



Contribute your code and comments through Disqus.

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.