john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

exceptions classes try catch throw suppress

$my_file = @fopen('non_existent_file');  //suppress warning
if (!$my_file ) {
  return false;   //custom error handling
}


<?php

try
{
    $error_message = "Hello, I am an error.";
    throw new Exception($error_message);
}
catch (Exception $e)
{
    echo "Exception caught: ",  $e->getMessage(), '\n';
}



/* classes allow a programmer to "store" a template that is re-useable.
When the class is "created" by the "new" command the code from the
template is then "live" for the compiler

They improve on header files: they can contain the default values of
variables, allow modularized access to the data (e.g. a programmer
using the Exception class doesn't need to know what happens inside the
"functions/methods" of the class)  and can be used as building blocks.

Note that in php5 the __construct() function is called automatically when
the object is created... similarly __destruct() is called when there are
no more references to the object or at the end of the PHP script.

Access to data/functions in a class are controlled by keywords: public (all)
 Protected (only within the object or inheritors), and Private (only to the
 object itself).
*/

class Exception
{
    protected $message = "Exception Thrown";
    protected $code = 0;
    protected $file;
    protected $line;

    function __construct($message = null, $code = 0);
    final function getMessage();
    final function getCode();
    final function getFile();
    final function getLine();
    final function getTrace();
    final function getTraceAsString();
    function __toString();
}
?>



<?php
/*when sending email, there's no PHP error if the recipient email
address is null, extending a class just adds more specific code to a class
 (template) that can be created (instantiated) using the "new" command

*/
class emailException extends Exception
{
    private $something;

    function __construct($message)
    {
        $this->something = "hello";
        echo "There was an error sending your email: <br \>";
        echo $message;
    }


    function sendEmail($to, $subject, $message)
    {
        if ($to == NULL)
        {
            throw new emailException ("Recipient email address is NULL");
        }
        mail($to, $subject, $message);
    }

    try {
        sendEmail("", "Exception Testing","We are testing the exception handling in PHP5");
    }
    catch (emailException $e)
    {
        echo " in file <strong>" . $e->getFile() . "</strong>";
        echo " on line <strong>" . $e->getLine() . "</strong>";
    }
?>

  • « phpunit pear dependencies codecoverage error resolution mock override
  • cherokee webserver php phpmyadmin »

Published

Jun 23, 2014

Category

php

~310 words

Tags

  • catch 1
  • classes 92
  • exceptions 4
  • php 82
  • suppress 1
  • throw 1
  • try 3