php 重新抛出异常,PHP从构造函数重新抛出异常

博客讨论了在PHP类构造函数中处理异常的常见做法。通常,当构造函数内的初始化方法可能抛出异常时,是否应该在捕获后重新抛出异常。文章指出,简单的异常处理代码可能导致不必要的代码重复,并提出重构建议,即直接抛出异常而无需额外的捕获块。这样做简化了代码,但可能会导致在构造函数外部无法区分不同类型的异常。
摘要由CSDN通过智能技术生成

只是想知道这是否是一种常见做法.基本上构造函数正在调用一些失败的初始化函数.我的想法是,将异常重新抛回到创建对象的位置是有意义的,因为这是发送实际输出的地方.

对于这种情况,这是“最佳做法”吗?或者有更标准的方法来做到这一点?

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

}

?>

解决方法:

我们只看到这部分代码:

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

}

因为InvalidArgumentException也是一个Exception,这是典型的代码复制案例,本身可以简化为:

try {

$this->x = $this->functionThatMightThrowException($filename);

$this->y = $this->doSomethingElseThatMightThrow();

}

catch(Exception $e) {

throw $e; //again

}

现在,您询问这是否良好实践的路线已经消失.所以我想即使采用这种纯系统的方法来删除重复的代码,问题也可以回答:不,这不是好的做法.这就是代码重复.

接下来 – 已经评论过 – 重新抛出异常没有任何价值.所以代码甚至可以减少到:

$this->x = $this->functionThatMightThrowException($filename);

$this->y = $this->doSomethingElseThatMightThrow();

所以我希望这会有所帮助.代码与以前完全相同,没有区别,只需要更少的代码,这总是受欢迎的.

标签:php,oop,exception-handling

来源: https://codeday.me/bug/20190831/1776939.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值