PHP Exception

Beginner
7 min read
Updated: Nov 2026
3 examples
Throw, catch & inspect

Definition and Usage

An Exception is a PHP object that represents a problem your program can catch and handle. You create one with throw new Exception("..."), catch it with catch (Exception $e), then read details such as the message, code, file, and stack trace.

__construct() stores the message, code, and optional previous Throwable. After you catch the object, use getMessage(), getCode(), getFile(), and getLine() for the basics, or getTraceAsString() for a printable stack.

This page explains the ideas. The Exception Methods index lists all 10 method guides.

Catch the type you need.

Use catch (Exception $e) for normal application exceptions. In PHP 7+, you can also catch Throwable to handle both Exception and Error objects.

Exceptions cannot be cloned.

clone $e raises an Error. Rethrow the same instance, or wrap it with a new Exception and pass the old one as previous.

PHP Syntax

The usual throw, catch, and inspect pattern:

PHP
try {
    throw new Exception("Something went wrong", 100);
} catch (Exception $e) {
    $e->getMessage();          // string message
    $e->getCode();             // int code
    $e->getFile();             // file where it was created
    $e->getLine();             // line where it was created
    $e->getPrevious();         // previous Throwable or null
    $e->getTrace();            // stack as array
    $e->getTraceAsString();    // stack as string
    echo $e;                   // calls __toString()
}

// Chain a previous cause
throw new Exception("Outer failure", 1, $previous);

Core Ideas

What to remember when you work with Exception in PHP:

IdeaExampleRemember
Throwthrow new Exception("...")Stops normal flow and jumps to a matching catch
Catchcatch (Exception $e)Handles the object; use Throwable to catch Errors too
Message$e->getMessage()Human-readable text for logs or UI
Code$e->getCode()Your own integer category; default is 0
LocationgetFile(), getLine()Where the exception was created, not where it was caught
Chainingnew Exception($msg, $code, $prev)Keep the root cause behind a friendlier outer message
StackgetTrace(), getTraceAsString()Array for code, string for quick logs
No cloningclone $eRaises an Error; wrap or rethrow instead

PHP Examples

Three short scripts that show how Exception works in PHP. Replace the messages with your own.

Example 1 — Throw and catch

Throw an Exception with a message and code, then read both from the catch block.

PHP
<?php
try {
    throw new Exception("User id is missing", 400);
} catch (Exception $e) {
    echo $e->getCode(), PHP_EOL;
    echo $e->getMessage(), PHP_EOL;
}
?>

How It Works

  1. throw new Exception(...) creates the object and leaves the try block.
  2. catch (Exception $e) receives that object.
  3. getCode() returns 400, and getMessage() returns the text.

Example 2 — Exception chaining

Wrap a low-level Exception so getPrevious() still reaches the original cause.

PHP
<?php
try {
    try {
        throw new Exception("Disk full");
    } catch (Exception $inner) {
        throw new Exception("Could not save file", 0, $inner);
    }
} catch (Exception $e) {
    echo $e->getMessage(), PHP_EOL;
    echo $e->getPrevious()->getMessage(), PHP_EOL;
}
?>

How It Works

  1. The inner throw is the technical root cause.
  2. The outer throw wraps it with a clearer message and passes $inner as previous.
  3. getPrevious() returns that earlier Exception so both messages stay available.

Example 3 — Message vs stack string

Compare getMessage() with the start of getTraceAsString().

PHP
<?php
function boom(): never
{
    throw new Exception("Boom");
}

try {
    boom();
} catch (Exception $e) {
    echo $e->getMessage(), PHP_EOL;
    $lines = explode("\n", $e->getTraceAsString());
    echo $lines[0], PHP_EOL;
}
?>

How It Works

  1. getMessage() returns only the short text Boom.
  2. getTraceAsString() returns the printable stack.
  3. The first line shows the boom() frame closest to the throw.

Next: PHP Exception Methods Index

After you know throw, catch, and the main getters, open the methods index for all 10 guides.

Start withWhy
__construct()Create an Exception with message, code, and previous
getMessage()Read the exception message
getPrevious()Walk a chain of nested causes
getTraceAsString()Log a printable stack trace
__clone()Learn why exceptions cannot be cloned

Full list: PHP Exception Methods index (/php/exception/function).

Frequently Asked Questions

Exception is the base class for errors you can catch during normal program flow. You throw an Exception with throw new Exception(...), catch it with catch (Exception $e), then read details with methods such as getMessage() and getCode().
Both implement Throwable and can be thrown or caught. Exception is for recoverable application problems. Error is for serious runtime problems such as TypeError. Beginners usually start with Exception in try and catch.
Call getMessage() on the caught object. For a longer developer report that includes the stack, cast the exception to a string or call __toString() / getTraceAsString().
When you catch one Throwable and throw a new Exception, pass the old one as the third constructor argument. Later getPrevious() returns that earlier cause so logs keep both the friendly message and the root error.
No. Exception::__clone() is final and private, so clone $e raises an Error. Rethrow the same object or create a new Exception that wraps the old one.
Practice the examples here, then open the Exception Methods index for all 10 method guides, from __construct() and getMessage() to getTraceAsString() and __clone().

Browse every Exception method

Open the methods index for categorized guides with examples and FAQs.

Exception Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful