Announcement

Collapse
No announcement yet.

What are object oriented exceptions / exception handlers - How do I use them?

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • What are object oriented exceptions / exception handlers - How do I use them?

    A better and more convenient way of catching errors is using Exception Handlers. The code to be executed and tested for errors is within the try block, and if errors occurred, the catch block is executed - where an error is usually output to the end user or returned to another method within the application, perhaps. An example is below:

    PHP Code:
    <?php
    try
    {
    return new 
    PDO("mysql:dbname=cpanel_username_db_name;host=localhost","cpanel_username_db_user","pw_here");
    }
    catch(
    PDOException $error// $error returns error from PDOException class
    {
    echo 
    "<p><b>Database connection error.</b></p>";
    echo 
    "<p>".$error->getMessage()."</p>";
    die();
    }
    ?>
    In this case, the instantiation of the PDO class is tested. If there is a problem with the connection details for example, then that is obviously an error, so an error is going to be thrown. If any Exceptions are thrown within the try block (for instance, by the PDO class), the catch block is then executed to catch the error or execute any extra code that you want executed if such event occurs, for example securely logging the error in a hidden text file (outside of public_html for example - the root directory).

    As you can see on the PDO class constructor page:

    PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.
    Misc. Questions

    What is "instantiation"?

    Instantiation (or creating an instance of) is the term to describe creating an instance of a class to use the functionality within a class. A class is merely a container until you create an instance of it in memory. Kind of like an installed application on your computer that is not being run. See: http://forums.eukhost.com/f50/object...ple-php-16963/

    What is the "class constructor"?

    The class constructor is like an ordinary method (or class "function") that is executed as soon as the class is instantiated. Essentially, it is a method of the class itself. For example, if you had a method called connect(), you would need to creating an instance of the class that method is part of, and then execute the method with that new instance. For example:

    PHP Code:
    <?php
    $instance 
    = new Class();
    $instance->connect(); // connect() method of the class called "Class"
    ?>
Working...
X