Jump to content

Custom Exception Class Draw-Backs?


Recommended Posts

Ok so I am currently rummaging through my head in order to find a decent ground work for error handling etc, I would like to know a couple things;

 

1. What are the general draw-backs of using the try/catch exception method (Anything you know or found in your journeys)?

 

2. In the below code you will see i have added a new argument to the 'CustomException' Class, $Object, this is so i can call methods from and/or serialize any property data from the offending class (Since all the exceptions will originate from a class). Will this hinder any functionality of the exception method (Again anything you know or have found in your journeys)?

 

Example Code for No.2:

// ++++ Generic Exception Classes
interface ClassExceptions
{
    /* Protected methods inherited from Exception class */
    public function getMessage();                 // Exception message
    public function getCode();                    // User-defined Exception code
    public function getFile();                    // Source filename
    public function getLine();                    // Source line
    public function getTrace();                   // An array of the backtrace()
    public function getTraceAsString();           // Formated string of trace
   
    /* Overrideable methods inherited from Exception class */
    public function __toString();                 // formated string for display
    public function __construct($Obejct, $message = null, $code = 0);
}

abstract class CustomException extends Exception implements ClassExceptions
{
    protected $message = 'Unknown exception';   // Exception message
    private   $string;                          // Unknown
    protected $code    = 0;                     // User-defined exception code
    protected $file;                            // Source filename of exception
    protected $line;                            // Source line of exception
    private   $trace;                           // Unknown
public	  $object;							// Referenced Object

    public function __construct($Object, $message = null, $code = 0){
	$this->object = $Object;
	parent::__construct($message, $code);
    }
   
    public function __toString()
    {
        return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
                                . "{$this->getTraceAsString()}";
    }
}

 

Thanks for your responses/input :).

 

-cb-

 

Note: Posted in 'Coding Help' as 'Application Design' seemed to general a topic. I expect this to be a coding question rather than a design question (No. 2).

Link to comment
Share on other sites

1. What are the general draw-backs of using the try/catch exception method (Anything you know or found in your journeys)?

 

The biggest draw-back of exception's is that when not caught, they leave your website in an unusable state to the end-user.

 

2. In the below code you will see i have added a new argument to the 'CustomException' Class, $Object, this is so i can call methods from and/or serialize any property data from the offending class (Since all the exceptions will originate from a class). Will this hinder any functionality of the exception method (Again anything you know or have found in your journeys)?

 

I can't yet find any draw-backs to this, but for what would you use it?

Link to comment
Share on other sites

Thanks for the info,

 

The biggest draw-back of exception's is that when not caught, they leave your website in an unusable state to the end-user.

So, any exceptions will need to be defined, is that what you mean? Since i have to throw an exception for it to be caught it would be only if i misspelled or tried to throw an undefined exception?

 

I can't yet find any draw-backs to this, but for what would you use it?

Oh I will be using this object for extra error information, My objects will retain error information specific to the functions being used, so having access to the object itself during an error should be quite useful in logging the error in as much detail as possible.

 

-cb-

Link to comment
Share on other sites

The biggest draw-back of exception's is that when not caught, they leave your website in an unusable state to the end-user.

 

So, any exceptions will need to be defined, is that what you mean? Since i have to throw an exception for it to be caught it would be only if i misspelled or tried to throw an undefined exception?

 

It's best to execute your program within a try/catch block with "catch (Exception $e)" to make sure no exception is left uncaught which is a likely case as your program is subject to change, new classes/exceptions can be introduced. And a slightest mistake may result in an unusable state for the end-user. A good example are some Java-based applications like Eclipse which has(/had?) a tendency to stop running while you were still writing code (due to some background tasks), something like:

 

Uncaught exception in package com.eclipse...

 

Really annoying.

 

I can't yet find any draw-backs to this, but for what would you use it?

 

Oh I will be using this object for extra error information, My objects will retain error information specific to the functions being used, so having access to the object itself during an error should be quite useful in logging the error in as much detail as possible.

 

I already thought you would say something like this but how do you know which methods the object exposes?

Link to comment
Share on other sites

Oh I will be using this object for extra error information, My objects will retain error information specific to the functions being used, so having access to the object itself during an error should be quite useful in logging the error in as much detail as possible.

 

-cb-

 

You're adding too much responsibility to your classes. If anything, let your classes pass a stadarised ErrorEvent object to exception.

I don't like how you're changing default argument order, but I guess there's hardly a way around it.

 

Also you have a typo in your interface's __construct() declaration.

Link to comment
Share on other sites

I find try...catch blocks to be result in cleaner code than the typical nested-if syndrome.  You just wrap an operation in try...catch and keep calling your objects until one throws an exception.  Of course at a deeper level in your code you still have the nested-if syndrome, but at least its not exposed to code at the more "abstract" or outer level of logic.

 

As ignace has already suggested, you should run your program in a top-level exception handler.

 

I use mod_rewrite in all of my programs to send all necessary requests through index.php and then my index.php tends to look like this:

 

<?php
define( 'APP_DIR_HOME', dirname( __FILE__ ) );
define( 'APP_DIR_APP', APP_DIR_HOME . '/app' );
define( 'APP_DIR_CLASSES', APP_DIR_APP . '/classes' );
// more defines...
require_once( APP_DIR_CLASSES . '/Site.php' );

try {
  $site = Site::getInstance();
  $site->run();
}catch( Exception $ex ) {
  Site::TopLevelException( $ex );
}
?>

 

My Site::TopLevelException usually does the following:

1) Generate a unique ID, call it UniqueID

2) Log the exception message and UniqueID to APP_DIR_LOGS . '/errors.txt'

3) Display a message to the user of the form:

Your most recent action has resulted in an unexpected condition; please try again or call support with ID# <UniqueID-goes-here>

 

A) I can use exception-based error-handling throughout my project, which means code at a higher level of logic is usually cleaner.

B) Users are not exposed to nasty error and exception messages.

C) If an exception I have not planned for is thrown, my program displays a more friendly message to the user in addition to an ID I can use to find the exact exception in my log file.

Link to comment
Share on other sites

B) Users are not exposed to nasty error and exception messages.

C) If an exception I have not planned for is thrown, my program displays a more friendly message to the user in addition to an ID I can use to find the exact exception in my log file.

 

True, but it also leaves your application in an unusable state and the back-button may not be an option as it may contain the root-cause (eg POST) resulting in the user re-entering the URL (think reboot the application/system).

 

It's good to log exceptions and the usage of an ID/support-ticket is more then ideal, but with some added features you could increase usability:

 

catch (Exception $e) {
  $ID = Site::TopLevelException($e);//log & return ID
  // this page is mostly static
  include('errors/uncaught-exception.php');//display's support-ID and provides extra information + options
  exit(0);
}

 

A click is easier then manually re-entering the entire URL

Link to comment
Share on other sites

but it also leaves your application in an unusable state

In most instances an exception caught at the top-level does mean the application is in an unusable state.  This would most like occur when active directory, a domain server, or the database server is unavailable.  In those instances, my application can't be used.  :)

Link to comment
Share on other sites

but it also leaves your application in an unusable state

In most instances an exception caught at the top-level does mean the application is in an unusable state.  This would most like occur when active directory, a domain server, or the database server is unavailable.  In those instances, my application can't be used.  :)

 

Not every uncaught exception has something to do with a failing DB server although it is possible. Even in that case I would give them the option to return to the frontpage or something, even if it's the case that the DB server is unresponsive. This in turn will throw another exception with more details. Not all clients just jump to the phone when something happens, some really try to figure out what is wrong, to be able to give a very accurate description of the problem.

 

It's just to let the client feel that the application isn't entirely dead and provide some minimal form of functionality. Like when the DB fails it would save the text in a file instead of resulting in a complete loss.

Link to comment
Share on other sites

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.