note 68256 added to language.exceptions

From: Date: Wed, 19 Jul 2006 21:06:26 +0000
Subject: note 68256 added to language.exceptions
Groups: php.notes 
Request: Send a blank email to php-notes+get-114949@lists.php.net to get a copy of this message
Here is a basic example of a way to mimick the convenience of exception handling in PHP4: <?php do { if (!$test_condition) { $error = 'test condition failed'; break; } if (!test_function()) { $error = 'test function failed'; break; } echo 'success!'; } while (false); if (isset($error)) { echo $error; } ?> Obviously this falls far short of PHP5 real exception handling in terms of normalisation. Also, $error won't propogate up the call stack like a real exception (i.e. test_function() can't itself throw an exception, nor call 'break'). But for me, the most important thing about exception handling is to be able to run through code and deal with errors separately, and not have to have a million nested IFs. Compare that code to this: <?php if (!$test_condition) { $error = 'test condition failed'; } elseif (!test_function()) { $error = 'test function failed'; } else { echo 'success!'; } if (isset($error)) { echo $error; } ?> At first this seems no more cumbersome, but what if test_function took arguments that required complicated preparation? You would need a mess like this: <?php if (!$test_condition) { $error = 'test condition failed'; } else { $fooRes = mysql_query('SELECT foo FROM bar LIMIT 1'); $fooRow = mysql_fetch_assoc($fooRes); if (!test_function($fooRow)) { $error = 'test function failed'; } else { echo 'success!'; } } ?> Obviously this could get out of hand quickly. In the first example, you can just prepare the argument before the 'if (!test_function($fooRow))', and on the same nesting level. This method is also somewhat more flexible in that you can generate 'exceptions', and then deal with them much later (which may be desirable if they aren't really threatening). In PHP5, a catch block must always follow a try block directly. ---- Server IP: 66.207.199.35 Probable Submitter: 24.42.73.194 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/language.exceptions.php Edit -- http://master.php.net/note/edit/68256 Del: integrated -- http://master.php.net/note/delete/68256/integrated Del: useless -- http://master.php.net/note/delete/68256/useless Del: bad code -- http://master.php.net/note/delete/68256/bad+code Del: spam -- http://master.php.net/note/delete/68256/spam Del: non-english -- http://master.php.net/note/delete/68256/non-english Del: in docs -- http://master.php.net/note/delete/68256/in+docs Del: other reasons-- http://master.php.net/note/delete/68256 Reject -- http://master.php.net/note/reject/68256 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#114949) next »