I'm interested in opinions on how to handle exceptions in the following situation.
Class A throws an exception from its constructor if something fails.
Class B's constructor creates an instance of class A. If anything fails in class B's constructor, I want it to throw an exception.
So, is there any benefit/reason for B to catch an exception from A if it fails, or does it make more sense to just let it slide through to the code that is trying to instantiate B. My feeling is that B should catch it, even if I will essentially just throw it again, but I can't make up my mind for sure (probably because I should be in bed and asleep ). Just wondered if there's a standard rule-of-thumb that would apply, or any best practice that would dictate which is better.
Example:
class A {
public function __construct() {
if($fullMoon && $tuesday)
{
throw new Exception(__METHOD__."(): Bad karma!");
}
}
}
// catch and throw again:
class B {
private $obj;
public function __construct() {
try {
$this->obj = new A();
}
catch(Exception $e) {
throw(__METHOD__."(): $e");
}
}
}
// let the caller worry about it:
class C {
private $obj;
public function __construct() {
$this->obj = new A();
}
}
try {
$test_b = new B();
$test_c = new C();
}
catch(Exception $e)
{
// do something with $e
}