Welcome to our comprehensive guide on PHP Exceptions! In this lesson, we'll explore what exceptions are, why they are essential, and how to use them effectively in your PHP projects. Let's dive in!
Exceptions are runtime errors that occur during the execution of a program. Instead of terminating the entire script, exceptions provide a way to handle errors gracefully and ensure your application continues to run smoothly.
In PHP, you can create custom exceptions or use built-in ones to handle various scenarios.
// Custom Exception
class CustomException extends Exception {
//...
}
// Built-in Exception
try {
// Code that may throw an exception
} catch (Exception $e) {
// Handle the exception
}PHP has three exception types:
throw new LogicalException("Division by zero error");throw new RuntimeException("Array key not found");throw new ErrorException("Out of memory error");Let's create a custom exception to handle a situation where a user tries to access a non-existent page.
// Custom exception
class PageNotFoundException extends Exception {
public function __construct($message = 'Page not found') {
parent::__construct($message);
}
}
// Example usage
try {
if (!file_exists('non_existent_page.html')) {
throw new PageNotFoundException();
}
} catch (PageNotFoundException $e) {
echo $e->getMessage();
}Sometimes, an exception can trigger another exception. In such cases, you can chain exceptions to provide more context.
try {
// Code that may throw an exception
} catch (Exception $e1) {
// Another exception triggered by the first one
throw new Exception("Exception chained: " . $e1->getMessage(), 0, $e1);
}You can also propagate exceptions to the calling function to let them handle the error.
function loadPage($page) {
if (!file_exists($page)) {
throw new PageNotFoundException();
}
//...
}
try {
loadPage('non_existent_page.html');
} catch (PageNotFoundException $e) {
echo $e->getMessage();
}Which of the following code snippets represents a custom exception in PHP?
Hope you found this PHP Exceptions Introduction helpful! In the next lesson, we'll dive deeper into exception handling best practices and advanced techniques. Keep coding! π»π