Error Handling and Exceptions in PHP – Writing Reliable Code
Why Is Error Handling Important?
Every developer writes code that fails at some point. Proper error handling ensures your application doesn’t crash or expose sensitive data to users. Instead, it helps:
- Show user-friendly error messages
- Log technical issues internally
- Prevent full application breakdown
- Maintain a smooth user experience
Types of Errors in PHP
Type | Description |
---|---|
Parse Errors | Syntax mistakes that prevent code from running |
Fatal Errors | Critical issues that stop execution |
Warnings | Non-fatal issues; execution continues |
Notices | Minor issues, like undefined variables |
Exceptions | Errors that can be caught and handled using try...catch |
Exceptions are ideal for modern apps and are widely used in object-oriented PHP and frameworks like Laravel.
The try
, catch
, and finally
Blocks
Basic Syntax:
try {
// Code that may throw an exception
} catch (Exception $e) {
// Code that runs if exception occurs
} finally {
// Optional: runs regardless of success/failure
}
Example:
<?php
try {
echo "Attempting something risky...<br>";
throw new Exception("Something went wrong!");
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "<br>Cleaning up resources.";
}
?>
Output:
Attempting something risky...
Error: Something went wrong!
Cleaning up resources.
Throwing Your Own Exceptions
Use the throw
keyword to manually trigger an exception.
Example:
function divide($a, $b) {
if ($b == 0) {
throw new Exception("Cannot divide by zero.");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Custom Exception Classes
You can define your own exception types by extending PHP’s Exception
class.
Example:
class LoginException extends Exception {}
function checkLogin($user) {
if ($user !== "admin") {
throw new LoginException("Unauthorized user");
}
return "Access granted";
}
try {
echo checkLogin("guest");
} catch (LoginException $e) {
echo "Login Error: " . $e->getMessage();
}
Logging Errors Instead of Displaying
Never show raw errors to users on live websites. Instead, log them.
Enable Logging in PHP:
In your php.ini
file or script:
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');
Log an Error:
error_log("A database error occurred at " . date('Y-m-d H:i:s'));
Logs can be reviewed by developers later for debugging.
Real-World Example: Form Validation with Exception
function validateEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception("Invalid email address");
}
return true;
}
try {
validateEmail("invalid-email");
} catch (Exception $e) {
echo "Validation failed: " . $e->getMessage();
}
Best Practices
- Always catch exceptions before they crash the app
- Create custom exceptions for different error types
- Log errors instead of showing them in production
- Use
finally
to clean up database connections, file handles, etc. - Never reveal sensitive error details to users
Common Mistakes to Avoid
- Ignoring errors or suppressing them with
@
- Not wrapping risky operations inside
try...catch
- Showing raw
Exception
details to users - Forgetting to validate input before using it
Notes:
- PHP errors can be caught and handled using exceptions
- Use
try
,catch
, andfinally
to manage risky code safely - Throw exceptions for predictable issues (invalid input, failed queries)
- Logging is essential in production apps
- Custom exceptions help write modular, readable code
Practice Tasks
Task 1: Division Exception
Create a function that divides two numbers. Throw an exception if the divisor is zero.
Task 2: User Login Exception
Write a class Auth
with a method checkUser($username)
that throws an exception if the username isn’t “admin”.
Task 3: Logging Mechanism
Add error logging for a simulated “File not found” error using error_log()
.
💡 Explore More PHP Learning Tools & Resources
PHP Practice Quiz
Test your PHP skills with real coding questions and scoring.
PHP Interview Questions
Prepare for interviews with common PHP questions and answers.
Educational AI Tutor
Ask PHP questions and get instant AI-powered explanations.
Question Generator
Auto-generate PHP interview questions for quick practice.