💡 Ask Tutor

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

TypeDescription
Parse ErrorsSyntax mistakes that prevent code from running
Fatal ErrorsCritical issues that stop execution
WarningsNon-fatal issues; execution continues
NoticesMinor issues, like undefined variables
ExceptionsErrors 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:

PHP
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
<?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:

JavaScript
Attempting something risky...  
Error: Something went wrong!  
Cleaning up resources.

Throwing Your Own Exceptions

Use the throw keyword to manually trigger an exception.

Example:

PHP
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:

PHP
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:

PHP
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

Log an Error:

PHP
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

PHP
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, and finally 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().