Re: PHP5 exception handling
| From: | Curt Zirzow | Date: | Fri, 30 Jul 2004 15:57:15 +0000 |
| Subject: | Re: PHP5 exception handling | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-192322@lists.php.net to get a copy of this message | ||
* Thus wrote Matthew Weier O'Phinney:
>
> The problem I'm running into: what do I pass as arguments to catch()?
> The articles on ZE2 use something like: catch (Exception $e) {}, or
> something like catch(MyException $e) (where MyException is a class they
> defined in their examples). Is the 'Exception' class a base
> class/handler with PHP5? Do I need to create my own exception handler
> classes? Do I even need to catch objects of a specific type, or can I
> simply do:
> catch ($error) {
> do something with $error
> }
At minimum you should always at least catch the Exception class:
catch (Exception $e) { }
If the class instance your calling throws a custom exception
definition you can attempt to catch that before the standard
Exception class:
<?php
class MyException extends Exception {
/* Redefine the exception so message isn't optional */
public function __construct($message, $code = 0) {
// custom stuff you want to do..
// ...
parent::__construct($message, $code);
}
/* custom string representation of object */
public function __toString() {
return __CLASS__ . " [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A Custom function for this type of exception\n";
}
}
class foo {
function myException() {
throw new MyException('Exception thrown');
}
function standardException() {
throw new Exception();
}
}
$f = new foo();
try {
$f->myException();
}
catch (MyException $e) {
echo "Caught my exception\n", $e;
$e->customFunction();
}
catch (Exception $e) {
echo "Default Exception caught\n", $e;
}
try {
$f->standardException();
}
catch (MyException $e) {
echo "Caught my exception\n", $e;
$e->customFunction();
}
catch (Exception $e) {
echo "Default Exception caught\n", $e;
}
HTH,
Curt
--
First, let me assure you that this is not one of those shady pyramid schemes
you've been hearing about. No, sir. Our model is the trapezoid!