Skip to main content

Creating a custom exception handler

Let's start by understanding what Exceptions are. Exceptions are a way of signaling that an unexpected situation or error has occurred while executing our program. PHP 5 has an exception model similar to that of other programming languages.

In PHP, an exception can be thrown and caught using the throw and catch keywords, respectively. However, what if we want to create our own custom exceptions and exception handler? Let's learn how to do this.

Creating a Custom Exception Class

In PHP, the Exception class is available by default. To create a custom exception, we need to define a new class that extends the Exception class.

Here's how we can do it:

class CustomException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

In this class, we have a public method errorMessage(). This method returns an error message including the file name, error line, and custom error message.

Throwing a Custom Exception

To use our custom exception, we can throw it using the throw keyword:

$email = "[email protected]";

try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw user error
throw new CustomException($email);
}
} catch (CustomException $e) {
//display custom message
echo $e->errorMessage();
}

Here, if the email is not valid, a CustomException is thrown. The catch block catches it and displays a custom error message.

Creating a Custom Exception Handler

PHP allows us to set a custom exception handler function using set_exception_handler(). This function can take the name of the function to be called when an uncaught exception occurs.

Here's how we can do it:

function customExceptionHandler($exception) {
echo "Caught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('customExceptionHandler');

throw new Exception('Uncaught Exception occurred');

In this code, we first define our custom exception handler function customExceptionHandler(). Then, we set it as our exception handler. Now, when an uncaught exception occurs, our custom function is automatically called.

Remember, the custom exception handler function will not handle exceptions that are already caught in a catch block.

That's all there is to creating custom exceptions and exception handlers in PHP. With this knowledge, you can create more complex and specific exception handling behaviors in your PHP applications. Happy coding!