How can namespaces be used to specify which Exception class to use in PHP?
When working with multiple libraries or frameworks in PHP, there may be situations where different Exception classes have the same name. To specify which Exception class to use, namespaces can be used to differentiate between them. By specifying the full namespace of the Exception class when catching or throwing an exception, PHP will know exactly which class to use.
<?php
use MyNamespace\Exception\CustomException;
try {
// Some code that may throw an exception
throw new CustomException("An error occurred.");
} catch (CustomException $e) {
echo "Caught CustomException: " . $e->getMessage();
} catch (Exception $e) {
echo "Caught generic Exception: " . $e->getMessage();
}
Keywords
Related Questions
- Why is it important to consider context when inserting values into HTML code in PHP?
- In PHP, what are the advantages of using the ON DUPLICATE KEY UPDATE clause in an INSERT statement for handling duplicate records in a database table?
- What best practices should be followed when setting the root directory for templates in PHP?