只是想知道这是否是一种常见的做法。基本上这个构造函数正在调用一些导致失败的初始化函数。我的想法是,将异常重新引回到创建对象的位置是有意义的,因为这是实际输出发送的地方。PHP从构造函数rethrow异常
这是这种情况的“最佳实践”吗?还是有更标准的方法来做到这一点?
<?php
class a {
private $x;
private $y;
function __construct($filename) {
try {
$this->x = $this->functionThatMightThrowException($filename);
$this->y = $this->doSomethingElseThatMightThrow();
}
catch(InvalidArgumentException $e) {
throw $e; //is this a good practice or not???
}
catch(Exception $e) {
throw $e; //again
}
}
//rest of class definition
}
// then somewhere else where the object is created and output is being sent
$fn = "blah.txt";
try {
$a = new a($fn);
}
catch (InvalidArgumentException $e) {
//actually handle here -- send error message back etc
}
catch (Exception $e) {
//etc
}
?>
如果你只是要重新抛出它,你为什么首先要抓住它? – PeeHaa
我会说这是多余的。别担心。让他们通过未被捕获的流行,不需要重新抛出它们。 – hakre
如果您没有捕捉到特定的异常,它将简单地执行备份执行链。捕捉并重新抛出相同的异常通常是毫无意义的。通常你只能抓到你实际想要处理的东西,然后让其他人上楼去处理。这就像自助餐:如果你不想吃东西,那么不要把它放在你的盘子上。 –