3.5. Exception Handling

Exception handling is a core feature of almost any programming language. Exception handling is not only necessary to detect errors but also for flow control. PHP provides a powerful exception-handling model that can easily be used by programmers. To show you how exception handling can be done, we have included a simple example:

<?php
        $a = "a string";
        if        (sqrt($a))
        {
                echo "Result: $b";
        }
        else
        {
                echo "The operation cannot be performed";
        }
?>

First, a string is defined. Then the script tries to compute the square root of the string, which is not possible. Therefore the condition evaluated by the if statement is not true and the else branch is entered.

If something happens that is not allowed in the script, it is necessary ...

Get PHP and PostgreSQL: Advanced Web Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.