Jump to content

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) ?: '';

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.