Jump to content

How do I use the new exceptions of Standard PHP Library (SPL)?


robsonrdasilva

Recommended Posts

Hi folks.

 

I've been studying about exceptions in PHP to improve my code, and I found the Standard PHP Library (SPL).

It's a library of functions that help to program.

 

There are many new exceptions, but I didn't find anyone example about it.

 

Do you know use it?

Those exceptions are like oldest exceptions?

 

Thanks.

Sure. Then you can easily catch specific types.

try {
doSomething();
} catch (DomainException $de) {
// bad input
} catch (RangeException $re) {
// bad output
} catch (Exception $e) {
// something else
}

Essentially, the SPL extension added a few things that the PHP core "should" have had from the start.

Sure. Then you can easily catch specific types.

try {
   doSomething();
} catch (DomainException $de) {
   // bad input
} catch (RangeException $re) {
   // bad output
} catch (Exception $e) {
   // something else
}

Essentially, the SPL extension added a few things that the PHP core "should" have had from the start.

 

 

I like to do it this way:

 

 

 

//Abstract/Exception.class.php
abstract class Abstract_Exception extends Exception
{
   abstract public function handle();
}


//Exception.class.php


class fatalError extends Abstract_Exception
{
   public function handle()
   {
      trigger_error(stripslashes(htmlentities($this->getMessage()), ENT_QUOTES), E_USER_ERROR);
   }
}


class runtimeError extends Abstract_Exception
{
   public function handle()
   {
      return '<div class="error">' . stripslashes(htmlentities($this->getMessage()), ENT_QUOTES) . '<>';
   }
}


//functions.php
function __autoload($class)
{
   static $includes;
   
   if ( !is_array($includes) )
      $includes = array();
     
   if ( !in_array($class, $includes) )
   {
      if ( stristr($class, 'Error') )
         $class = 'Exception';
      $includes[] = $class;
      $class      = str_replace('_', DIRECTORY_SEPARATOR, $class) . '.class.php';
      include $class;
   }
}


//some script
include 'functions.php';


try
{
   //code
   throw new fatalError('Couldn\'t connect to MySQL database.');
   
   //more code
   throw new runtimeError('You must enter a username.');
}
catch ( Exception $e )
{
   $error = $e->handle();
}


//html


echo isset($error) ?: '';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.