MVC Lesson 6: Understanding Exceptions & try..catch in Modern PHP

When you’re building robust PHP applications, error handling becomes critical. That’s where exceptions and the try..catch block come into play.

But let’s clear up a common misconception right away:

Exceptions ≠ try..catch block

They’re related — but not the same.


🚨 What is an Exception?

An exception is a special object in PHP used to represent an error or unexpected behavior. You use the throw keyword to create and “throw” an exception — essentially stopping normal code execution.

throw new Exception("Something went wrong!");

This line will immediately halt the code flow unless it’s caught.


🛡️ The try..catch Block

The try block wraps code that might fail. If an exception is thrown within that block, PHP looks for a catch block to handle it.

try {
    // Code that might throw an exception
    riskyFunction();
} catch (Exception $e) {
    // Handle the exception
    echo "Caught an exception: " . $e->getMessage();
}

🧠 Think of it this way:

  • try: “Try running this code.”
  • catch: “If it throws an exception, catch it and handle it here.”

If no exception is thrown, the catch block is ignored.


✅ Custom Exception Classes

You can even define your own exception types by extending PHP’s built-in Exception class.

class MyCustomException extends Exception {}

throw new MyCustomException("Custom error occurred!");

This is useful when you want to differentiate between different error conditions.


📌 Final Notes

  • You can throw exceptions without using try..catch, but PHP will stop execution unless they’re caught.
  • Always handle exceptions gracefully in production apps.
  • Use multiple catch blocks for different exception types if needed.

💡 Summary

  • Use throw to stop code and raise an exception.
  • Use try..catch to handle exceptions and keep your app running smoothly.
  • Build custom exceptions to organize and clarify your error handling.

Exception handling isn’t just a safety net — it’s a way to write cleaner, more predictable PHP code.