In PHP, an exception is a way to handle runtime errors in a structured way. Exceptions are objects that represent an error that occurred during the execution of a script.
To throw an exception in PHP, you can use the throw
keyword followed by an instance of the Exception
class or a child class of Exception
. Here’s an example:
<?php
// Throw an exception with a custom message
throw new Exception("An error occurred");
// Throw an exception with a custom code and message
throw new Exception("An error occurred", 123);
To catch an exception, you can use a try
block followed by a catch
block. The try
block contains the code that may throw an exception, and the catch
block contains the code that handles the exception.
Here’s an example of how to catch an exception in PHP:
<?php
try {
// Code that may throw an exception
} catch (Exception $e) {
// Code to handle the exception
}
In the catch
block, you can access the exception object using the $e
variable. You can use the getMessage
method of the exception object to get the error message, and the getCode
method to get the error code.
<?php
try {
// Code that may throw an exception
} catch (Exception $e) {
// Print the error message
echo $e->getMessage();
// Print the error code
echo $e->getCode();
}
You can also use multiple catch
blocks to handle different types of exceptions. For example:
<?php
try {
// Code that may throw an exception
} catch (MyCustomException $e) {
// Code to handle MyCustomException
} catch (Exception $e) {
// Code to handle other exceptions
}
In this case, the catch
block for MyCustomException
will be executed if an instance of MyCustomException
is thrown, and the catch
block for Exception
will be executed for all other exceptions.