PHP Try Catch and Exceptions

Like other programming languages, “Try catch” and exceptions exist in PHP. From PHP version 5 you can use try catch to control exceptions in PHP. In this article, we are going to discuss PHP “try catch” and exception with example.

PHP try catch

To catching of potential exceptions, you can use a try block. Each try must have at least one corresponding catch or finally block.

The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.

try {
    // run your code here
}
catch (exception $e) {
    //code to handle the exception
}
finally {
    //optional code that always runs
}

Try

Inside the try block, you can add the normal code that you want to control the exceptions.

Catch

When a PHP exception is thrown, the PHP runtime looks for a catch statement that can handle that type of exception. A catch block defines how to respond to a thrown exception.

This block of code will be called only if an exception occurs within the try code block. The code within your catch statement must handle the exception that was thrown.

A catch block defines one or more types of exceptions or errors it can handle, and optionally a variable to which to assign the exception.

Multiple catch blocks can be used to catch different classes of exceptions.

Finally

A finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

Finally is useful for more than just exception handling, it is used to perform cleanup code such as closing a file, closing a database connection, etc.

Note that, if you use the return statement inside the try block, finally block will be executed anyway.

Throw

The throw keyword is used to signal the occurrence of a PHP exception. The PHP runtime will then try to find a catch statement to handle the exception.

PHP Try Catch Example

try {
    for ($counter = -2; $counter < 3; $counter++) {
        echo 1 / $counter . "</br>";
    }
} catch (Exception $ex) {
    echo "Error: Division by zero. </br>";
}

Output

-0.5
-1
Warning: Division by zero
1
0.5

As we told you, the thrown object must be an instance of the Exception class or a subclass of Exception. In this example division by zero is not an instance of the Exception, then you can change the code like below.

function div($value)
{
    if (!$value) {
        throw new Exception("Error: Division by zero.");
    }
    return 1 / $value;
}

try {
    for ($counter = -2; $counter < 3; $counter++) {
        echo div($counter) . "</br>";
    }
} catch (Exception $ex) {
    echo "Error: Division by zero. </br>";
}

Output

-0.5
-1
Error: Division by zero. 

In code there is a division by zero, then the catch block will be executed.

function div($value)
{
    if (!$value) {
        throw new Exception("Error: Division by zero.");
    }
    return 1 / $value;
}

try {
    for ($counter = -2; $counter < 3; $counter++) {
        echo div($counter) . "</br>";
    }
} catch (Exception $ex) {
    echo "Error: Division by zero. </br>";
} finally {
    echo "This is finally block.";
}

Output

-0.5
-1
Error: Division by zero.
This is finally block.

This example shows that finally block will be executed if there is an exception or not.

If you remove the catch block, if there is an exception, a Fatal error will be displayed.

PHP try catch with multiple exception types

PHP supports using multiple catch blocks within try catch. This allows us to customize our code based on the type of exception that was thrown.

function div($value)
{
    if (!$value) {
        throw new Exception("Error: Division by zero.");
    }
    return 1 / $value;
}

try {
    for ($counter = -2; $counter < 3; $counter++) {
        echo div($counter) . "</br>";
    }
} catch (Exception $ex) {
    echo $ex->getMessage();
} catch (InvalidArgumentException $ex) {
    echo $ex->getMessage();
}

Creating custom PHP exception types

PHP also allows you to create custom exception types. To create a custom exception handler, you must create a special class with functions that can be called when an exception occurs. The class must be an extension of the exception class.

class DivisionByZero extends Exception
{
    public function errorMessage()
    {
        return "Error: Division by zero.";
    }
}

function div($value)
{
    if (!$value) {
        throw new DivisionByZero();
    }
    return 1 / $value;
}

try {
    for ($counter = -2; $counter < 3; $counter++) {
        echo div($counter) . "</br>";
    }
} catch (DivisionByZero $ex) {
    echo $ex->errorMessage();
}

Output

-0.5
-1
Error: Division by zero.

You may like

Shopping Cart