CodeBlanks Logo Icon CodeBlanks

The Exception class

PHP course · Intermediate · Lesson 101/115

Learn the Exception class's getMessage(), getCode() and getTrace() methods.

Methods of the Exception class

The Exception object carries information about the error. You use five common methods.

getMessage() returns the message, getCode() returns the error code. getFile() and getLine() show where the error was thrown. getTrace() returns the call stack as an array.

You call them in the catch block to report the error or write it to a log.

The code and the second argument

The second argument to the Exception constructor is a numeric code: new Exception('Unauthorized', 403). This code can be an HTTP status, an error number or any application-defined value.

In the catch block you read it with $e->getCode(). The code is useful to distinguish errors programmatically; the message is for humans and is shown directly.

Exercise Print the exception details

Inside a try block, throw new Exception("Invalid user", 403). In the catch (Exception $e) block, print getMessage() and getCode() on separate lines.

Show example solution
Inside try, call throw new Exception("Invalid user", 403). In catch (Exception $e), write echo $e->getMessage() . "\n"; and echo $e->getCode() . "\n";.
Example solution:
<?php
// Throw an exception and print getMessage/getCode
try {
    throw new Exception("Invalid user", 403);
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
    echo $e->getCode() . "\n";
}

Test yourself

  1. Match the methods

    getMessage()
    Returns the message
    getCode()
    Returns the code
    getTrace()
    Returns the call stack
    getFile()
    Returns the file name
  2. Read the code

    <?php
    try {
        throw new Exception("Error", 42);
    } catch (Exception $e) {
        echo $e->____();
    }
    
    Show answer
    <?php
    try {
        throw new Exception("Error", 42);
    } catch (Exception $e) {
        echo $e->getCode();
    }
    
  3. What does 42 mean in new Exception('Error', 42)?

    • The error code
    • The error line number
    • The error file
    • The error priority
    Show answer

    The error code — Correct. 42 is the second argument to the Exception constructor; it is read with getCode().

All lessons in Intermediate