15. Error Handling (PHP)

Error handling in PHP helps you detect, manage, and debug issues in your code efficiently.


🔴 1. Error Types in PHP

PHP has different types of errors:

✅ Common Error Types:

Error TypeDescription
E_NOTICEMinor issues (e.g., undefined variable)
E_WARNINGNon-fatal errors (script continues)
E_ERRORFatal error (script stops)
E_PARSESyntax errors
E_DEPRECATEDUsing outdated features
E_ALLAll errors

📌 Example:

echo $name; // Undefined variable → Notice

🟡 2. Displaying Errors

Enable error reporting:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Disable in production:

ini_set('display_errors', 0);

🟢 3. try-catch Blocks (Exception Handling)

Used to handle runtime errors (exceptions).

📌 Basic Example:

try {
$num = 10 / 0;
} catch (Throwable $e) {
echo "Error: " . $e->getMessage();
}

📌 Custom Exception:

function checkAge($age) {
if ($age < 18) {
throw new Exception("Underage!");
}
return "Access granted";
}try {
echo checkAge(16);
} catch (Exception $e) {
echo $e->getMessage();
}

🔵 4. Custom Error Handling

You can create your own error handler.

📌 Example:

function customError($errno, $errstr) {
echo "Error [$errno]: $errstr";
}set_error_handler("customError");// Trigger error
echo $test; // undefined variable

🟣 5. Trigger Custom Errors

trigger_error("Something went wrong!", E_USER_WARNING);

🟠 6. Debugging Techniques

✅ 1. Print Variables

print_r($data);
var_dump($data);

✅ 2. Use die() / exit()

die("Stop here");

✅ 3. Logging Errors

error_log("This is an error message", 3, "error.log");

✅ 4. Stack Trace

try {
throw new Exception("Test error");
} catch (Exception $e) {
echo $e->getTraceAsString();
}

🔥 7. Best Practices (Important)

  • ❌ Don’t show errors to users in production
  • ✅ Log errors instead
  • ✅ Use try-catch for critical operations
  • ✅ Validate inputs properly
  • ✅ Use custom error handlers for large apps

🚀 Real-World Example

try {
$conn = new mysqli("localhost", "root", "", "test"); if ($conn->connect_error) {
throw new Exception("Database connection failed");
} echo "Connected successfully";} catch (Exception $e) {
error_log($e->getMessage());
echo "Something went wrong. Please try later.";
}