Re: Continued try blocks
| From: | Amaury Bouchard | Date: | Fri, 26 Apr 2013 19:52:16 +0000 |
| Subject: | Re: Continued try blocks | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-67177@lists.php.net to get a copy of this message | ||
2013/4/26 Andreas Heigl <andreas@heigl.org>
> try {
> $foo = $bar->getObject();
> $foo->doSomething()
> } catch(Exception $e) {
> continue // Or whatever shall be used
> }
>
> When $bar->getObject throws an Exception no $foo is set. So the next
> line will result in a "PHP Fatal error: Call to a member function
> doSomething() on a non-object".
>
That's fine to me.
It's a software engineering problem you can solve easily:
try {
$foo = $bar->getObject();
$foo->doSomething();
} catch (ObjectCreationException $oce) {
add_to_log('Unable to create object');
throw $oce; // or do something else,
// or just do nothing to exit from the try/catch block
} catch (Exception $e) {
add_to_log($e->getMessage());
continue;
}
The getObject() method should raise an ObjectCreationException, while the
doSomething() method could raise any other type of exception.
It's just a natural and smart way to use exceptions.
It could be solve differently:
try {
$foo = $bar->getObject();
$foo->doSomething();
} catch (NotImportantException $nie) {
add_to_log($nie->getMessage());
continue;
} catch (Exception $e) {
add_to_log($e->getMessage());
throw $e; // or do something else,
// or just do nothing to exit from the try/catch block
}
If an expression raises a NotImportantException, it will not interrupt the
execution flow.