Exceptions

What is an exception?

An exception is a controlled way to signal that the program has reached an invalid or unsafe state and cannot continue normally.

Unlike warnings or notices, exceptions are intentional. They are thrown by the developer or by PHP itself to stop normal execution and force the error to be handled explicitly.

An exception does not mean “something broke randomly”.
It means “this situation should not happen, and continuing would be incorrect”.

Why exceptions exist

Exceptions separate normal logic from error handling.

Instead of checking every possible failure with if statements, you write code assuming valid conditions. When something invalid happens, an exception interrupts the flow and moves execution to a place designed to handle failure.

This makes code:

  • easier to read
  • safer
  • harder to misuse silently

Throwing an exception

An exception is thrown using the throw keyword.

When throw is executed:

  • the current function stops immediately
  • PHP exits the current execution path
  • PHP looks for the nearest try block that can catch it

If no matching catch exists, the script terminates with a fatal error.

Catching an exception

Exceptions are handled using try and catch.

Code inside try runs normally.
If an exception is thrown inside try, execution jumps directly to catch.
The rest of the try block is skipped.

Catching an exception prevents script termination and allows controlled recovery.

The finally block

The finally block always executes:

  • when no exception occurs
  • when an exception is caught
  • right before execution continues or exits

It is used for cleanup, logging, or guaranteed output.

The Exception object

When an exception is caught, PHP provides an Exception object.

This object contains:

  • a message describing the error
  • an optional numeric code
  • the file where the exception was thrown
  • the line number where it occurred
  • an optional previous exception

This makes exceptions useful both for flow control and debugging.

Uncaught exceptions

If an exception is thrown and not caught:

  • PHP triggers a fatal error
  • execution stops immediately
  • a stack trace is generated

This behavior is intentional. Silent failures are worse than hard failures.

Key mental model

Exceptions are not “special errors”.
They are signals that the program state is invalid.

Normal path: assume things are correct.
Exceptional path: stop everything and handle the failure explicitly.