/

How to Use Exceptions in PHP

How to Use Exceptions in PHP

Errors can occur unexpectedly in our code, but by using exceptions in PHP, we can handle them in a more controlled manner. Exceptions allow us to intercept errors and take appropriate actions, such as displaying error messages or implementing workarounds.

To use exceptions, we wrap the code that might potentially raise an exception in a try block, followed by a catch block. The catch block is executed if there is an exception in the preceding try block. Here is the basic structure:

1
2
3
4
5
try {
// code that might raise an exception
} catch (Throwable $e) {
// actions to take when an exception occurs
}

In the catch block, we can access the Exception object $e to gather more information about the exception. For example, we can retrieve the error message using $e->getMessage().

Let’s consider an example where a number is divided by zero:

1
2
3
4
5
try {
echo 1 / 0;
} catch (Throwable $e) {
echo $e->getMessage();
}

Without exception handling, this operation would result in a fatal error and halt the program. But by using exceptions, we can gracefully handle the error and display the problem to the user.

Exceptions can be further refined by utilizing different exception classes. For instance, we can catch the specific DivisionByZeroError exception to handle division by zero errors differently. Additionally, we can have a catch-all block for any throwable error at the end:

1
2
3
4
5
6
7
try {
echo 1 / 0;
} catch (DivisionByZeroError $e) {
echo 'Oops! I divided by zero!';
} catch (Throwable $e) {
echo $e->getMessage();
}

To execute additional code after the try/catch structure, we can include a finally block. The code inside the finally block will be executed whether the preceding code had successful execution or an exception was caught:

1
2
3
4
5
6
7
8
9
try {
echo 1 / 0;
} catch (DivisionByZeroError $e) {
echo 'Oops! I divided by zero!';
} catch (Throwable $e) {
echo $e->getMessage();
} finally {
echo ' ...done!';
}

In addition to using the built-in exceptions provided by PHP, you can create your own custom exceptions to handle specific cases. With exceptions, you have more control over error handling and can provide better user experiences.

tags: [“PHP”, “exceptions”, “error handling”]