Hello, please sign in or register
You are here: Home

Why Try Catch and Exception handling

Whats Try and Catch?

It's not Cricket. Its for [out-of] control-flow handling.

It took me a while to see the benefits of using the TRY...CATCH block. So to summarize If you want to jump from processing one chunk of code to another then there is no real way of doing it without writing the logic of the condition into everypart of your code... and exit(1) is a bit too draconian. This i found useful for nested/recursive function calls and callbacks etc. Whereby you may wish to move on their parent functions process/loop/position etc...

I'll try and come up with an example sometime

Setting up a default try catch is a good place to start

<?php

class My_Exception extends Exception
{
    public function reportException() {
        echo "A Custom function for this type of exception\n";
    }
}

function exception_handler($exception) {
    /**
     * Checks the class of the exception thrown. So we can mimic multiple CATCH blocks
     */
    switch ( get_class( $exception ) )
    {
        case "My_Exception":
            echo "Report: " , $exception->reportException(), "\n";
            break;
        default:
	     /**
	      * Else use default exception class
	      */
	     echo "Report: " , $exception->getMessage(), "\n";
    }
}

set_exception_handler('exception_handler');

throw new My_Exception('Uncaught Exception');
throw new Exception('Caught Exception string');

echo "Not Executed\n";

?>

What it doesn't do, FATAL errors!

One of the biggest glitches comes from FATAL errors which can be triggered by internal memory leaks, or failling libraries such as PREG here's an example using str_repeat. Here's a workaround from a post on php.net which catches runtime errors. But not syntax errors, unless already loaded (if file with syntax errors is included after the error handler here has been set)

<?php

echo "Hello";

function fatal_error_handler($buffer) {
  if (ereg("(error</b>:)(.+)(<br)", $buffer, $regs) ) {
    $err = preg_replace("/<.*?>/","",$regs[2]);
    error_log($err);
    return "ERROR CAUGHT check log file";
  }
  return $buffer;
}

function handle_error ($errno, $errstr, $errfile, $errline)
{
    error_log("$errstr in $errfile on line $errline");
    if($errno == FATAL || $errno == ERROR){
        ob_end_flush();
        echo "ERROR CAUGHT check log file";
        exit(0);
    }
}

ob_start("fatal_error_handler");
set_error_handler("handle_error");
str_repeat(str_repeat( " asdsdas dasd ", 100000 ), 1000);
//would normally cause a fatal error, but instead our output handler will be called allowing us to handle the error.
//somefunction();
ob_end_flush();
echo "Goodbye\n";

?>

 Breaking the script with Exception handler Wont Work!

<?php

function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
function exceptions_error_handler($severity, $message, $filename, $lineno) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
set_exception_handler('exception_handler');
set_error_handler('exceptions_error_handler', E_ALL^E_NOTICE);

str_repeat(str_repeat( " asdsdas dasd ", 100000 ), 1000);
try {
	str_repeat(str_repeat( " asdsdas dasd ", 100000 ), 1000);
	if ( true ) throw new Exception();
	echo "Dont see me";
}
catch( Exception $e ){    echo 'Caught exception: ',  $e->getMessage(), "\n";}
?>

 

References

 

Comments

wq123
This hilfiger outlet time swarovski jewelry something really timberland outlet strange, ...
Created 30/06/16
ninestab123
ninest123 One canada goose pas cher gucci outlet thing
Created 21/07/16
wanglili
air jordan retro coach outlet online coach outlet...
Created 21/08/17
Title*
Comment

Prove you are not a robot

To prove you are not a robot, please type in the six character code you see in the picture below
Security confirmation codeI can't see this!
Contact
Name*
Email never shown*
Home Page

Author

Andrew Dodson
Since:Feb 2007

Comment | flag

Categories

Bookmark and Share