note 68697 added to language.exceptions

From: Date: Tue, 08 Aug 2006 05:18:44 +0000
Subject: note 68697 added to language.exceptions
Groups: php.notes 
Request: Send a blank email to php-notes+get-115618@lists.php.net to get a copy of this message
Sometimes you want a single catch() to catch multiple types of Exception. In a language like Python, you can specify multiple types in a catch(), but in PHP you can only specify one. This can be annoying when you want handle many different Exceptions with the same catch() block. However, you can replicate the functionality somewhat, because catch(<classname> $var) will match the given <classname> *or any of it's sub-classes*. For example: <?php class DisplayException extends Exception {}; class FileException extends Exception {}; class AccessControl extends FileException {}; // Sub-class of FileException class IOError extends FileException {}; // Sub-class of FileException try { if(!is_readable($somefile)) throw new IOError("File is not readable!"); if(!user_has_access_to_file($someuser, $somefile)) throw new AccessControl("Permission denied!"); if(!display_file($somefile)) throw new DisplayException("Couldn't display file!"); } catch (FileException $e) { // This block will catch FileException, AccessControl or IOError exceptions, but not Exceptions or DisplayExceptions. echo "File error: ".$e->getMessage(); exit(1); } ?> Corollary: If you want to catch *any* exception, no matter what the type, just use "catch(Exception $var)", because all exceptions are sub-classes of the built-in Exception. ---- Server IP: 210.138.109.182 Probable Submitter: 61.213.152.134 (proxied: Version 1.1-Build_SOL_1126 $Date: 11/10/2005 17:46:0044$(IWSS)) ---- 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 -- https://master.php.net/note/edit/68697 Del: integrated -- https://master.php.net/note/delete/68697/integrated Del: useless -- https://master.php.net/note/delete/68697/useless Del: bad code -- https://master.php.net/note/delete/68697/bad+code Del: spam -- https://master.php.net/note/delete/68697/spam Del: non-english -- https://master.php.net/note/delete/68697/non-english Del: in docs -- https://master.php.net/note/delete/68697/in+docs Del: other reasons-- https://master.php.net/note/delete/68697 Reject -- https://master.php.net/note/reject/68697 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#115618) next »