Error Handling in PHP

Jussi Pohjolainen

TAMK University of Applied Sciences » ICT

PHP Error Handling

E_NOTICE

E_WARNING, E_ERROR and others

Setting Error Reporting Levels

Handling errors

Method errors

Exceptions

Exceptions

Example: throwing exception

function divide ($a, $b)
{
    if( ! (is_int($a)  and is_int($b)) )
    {
        throw new Exception();
    }
    if( $b === 0 )
    {
        throw new Exception();
    }
    
    return ( $a / $b );
}

Example: catching exception

try 
{
    $divide = divide( 3, 3 );
}
catch ( Exception $e )
{
    print "Problem";    
}

Creating your own Exception-classes

class AritmeticException extends Exception { }
class NumberFormatException extends Exception { }

function divide ($a, $b)
{
    if( ! (is_int($a)  and  is_int($b)) )
    {
        throw new NumberFormatException();
    }
    if( $b === 0 )
    {
        throw new AritmeticException();
    }
    
    return ( $a / $b );
}

Example: catching your own exception

try 
{
    $divide = divide( 3, 3 );
}
catch ( NumberFormatException $e )
{
    print "Please give integer-values";    
}
catch ( ArithmeticException $e )
{
    print "You cannot divide with 0";    
}

Exception class


class Exception
{
    protected $message = 'Unknown exception';   // exception message
    protected $code = 0;                        // user defined exception code
    protected $file;                            // source filename of exception
    protected $line;                            // source line of exception
    function __construct($message = null, $code = 0);
    final function getMessage();                // message of exception 
    final function getCode();                   // code of exception
    final function getFile();                   // source filename
    final function getLine();                   // source line
    final function getTrace();                  // an array of the backtrace()
    final function getTraceAsString();          // formated string of trace
    function __toString();                      // formated string for display
}

Making a better version of own Exceptions


class AritmeticException extends Exception 
{ 
    function __construct( $msg )
    {
        parent::__construct( $msg );
    }
}

function divide ($a, $b)
{
    if( ! (is_int($a)  and  is_int($b)) )
    {
        throw new NumberFormatException();
    }
    if( $b === 0 )
    {
        throw new AritmeticException("You cannot divide with zero");
    }
    
    return ( $a / $b );
}