Thoughts on exceptions

From: Date: Mon, 21 Aug 2000 16:16:58 +0000
Subject: Thoughts on exceptions
Groups: php.pear 
Request: Send a blank email to php-pear+get-195@lists.php.net to get a copy of this message
Hi, at the weekend a friend asked me what assert() is good for. Not beeing a C programmer I had to look it up eigther and we were wondering if it could be abused to simulate exception. Indeed it seems to be possible to map callback functions into exceptions. The first snippet demonstrates how it could work using lots of undocumented functions. It does not simulate the Java try-catch-throw functionality a 100%: - it lacks an exception stack - it calls the callback function before the try is finished (which may be an advantage in some cases) + similar code layout to Java But it gives you a similar code layout. In the second snipped I played around with an exception stack. This is also not perfect. The exception stack does not contain a caller-id and gets cleared completely with the next call to try_catch(). ... don't tell me that there's set_error_handler - I know. Anyway what do you think about the ideas? Could it be transformed into native PHP? Ulf +++ php4 only, exceptions without a stack +++ function try_catch($try, $catch) { global $lambda; $catch = 'global $php_errormsg; $exception = unserialize($php_errormsg); $catch'; $lambda = create_function("", $catch); assert_options( ASSERT_CALLBACK, $lambda); assert($try); } function throw($classname, $msg) { $level = error_reporting( E_ALL ); $exception = new $classname($msg); @trigger_error( serialize($exception) ); error_reporting ( $level ); } +++ php3, kind of a stack +++ function try_catch($try, $catch) { global $_exception_stack; $_exception_stack = array(); eval($try); if (0!=count($_exception_stack)) { eval($catch); $_exception_stack = array(); } } function throw($classname, $msg) { global $_exception_stack; if (!isset($_exception_stack)) $_exception_stack = array(); $exception = new $classname($msg); $_exception_stack[$classname] = $exception; } -- Ulf Wendel NetUSE AG, Siemenswall, 24107 Kiel, Germany Fon: +49 431 386435 00 -- Fax: +49 431 386435 99

« previous php.pear (#195) next »