PHP - Exceptions
The Throwable Interface
In PHP, exceptions are objects that represent exceptional conditions. They are thrown when a specific error occurs in your code. PHP provides the Throwable
interface, which is the base class for all exceptions and errors. It has several methods that allow you to handle exceptions effectively.
Basic Exception Handling
To handle exceptions in PHP, you can use the try-catch
block. Here's an example:
<?php
try {
// Code that might throw an exception
throw new Exception("An error occurred!");
} catch (Exception $e) {
// Code to handle the exception
echo "Caught exception: " . $e->getMessage();
}
?>
In this example, we use the throw
statement to create a new Exception
object with a custom message. If an exception is thrown within the try
block, the code execution jumps to the corresponding catch
block, where the exception is caught and handled.
set_exception_handler
The set_exception_handler
function allows you to define a custom function that will be called whenever an uncaught exception is thrown. This function should take two parameters: the exception object and a boolean indicating whether the exception was thrown during a call to eval()
.
Here's an example of how to use set_exception_handler
:
<?php
function myExceptionHandler($exception) {
echo "Uncaught exception: " . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
// Code that throws an exception
throw new Exception("Oops! Something went wrong.");
?>
In this example, we define a custom exception handler function called myExceptionHandler
. We then use set_exception_handler
to set this function as the default exception handler. When an uncaught exception is thrown, our custom function will be called instead of the default one.
SPL Exceptions
PHP provides several built-in exception classes in the Standard PHP Library (SPL). These classes extend the Exception
class and provide more specific information about different types of exceptions. Some common SPL exceptions include:
-
BadFunctionCallException
: Thrown when a callback refers to an undefined function or if some arguments are missing. -
DomainException
: Used for errors in the domain logic of your application. -
InvalidArgumentException
: Raised when a function is given an argument that it does not accept. -
LengthException
: Used when an operation attempts to use an object of the wrong length. -
OutOfBoundsException
: Thrown when an array index is out of bounds. -
OutOfRangeException
: Raised when a value is not within the expected range. -
RangeException
: Used when a value is not within the specified range. -
RuntimeException
: General purpose exception for runtime errors. -
UnderflowException
: Thrown when an underflow occurs (e.g., subtracting from an empty stack). -
UnexpectedValueException
: Raised when a value does not match with the expected type.
You can use these SPL exceptions in your code like any other exception class. For example:
<?php
function divide($a, $b) {
if ($b == 0) {
throw new DivisionByZeroError("Division by zero is not allowed.");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (DivisionByZeroError $e) {
echo "Caught exception: " . $e->getMessage();
}
?>
User-defined Exception
In addition to using built-in SPL exceptions, you can also create your own custom exception classes. To do this, simply extend the Exception
class and add any additional functionality you need. Here's an example:
<?php
class MyCustomException extends Exception {
public function __construct($message, $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
}
try {
throw new MyCustomException("This is a custom exception.");
} catch (MyCustomException $e) {
echo "Caught custom exception: " . $e->getMessage();
}
?>
In this example, we create a new class called MyCustomException
that extends the Exception
class. We then throw and catch an instance of this custom exception just like we would with any other exception.
By following these guidelines and using the provided tools, you can effectively handle exceptions in your PHP code and ensure that your applications are robust and resilient against unexpected errors. Remember to always test your code thoroughly and handle exceptions gracefully to provide a better user experience.
Credits: Image by storyset