【问题标题】:How to treat exceptions in constructor best?如何最好地处理构造函数中的异常?
【发布时间】:2011-04-08 10:50:09
【问题描述】:

如何在构造中以最佳方式处理异常?

option1 - 捕获创建对象的异常:

class Account {
    function __construct($id){
        if(empty($id)){
            throw new My_Exception('id can\'t be empty');
        }

        // ...
    }
}

class a1 {
    function just($id){
    try {
        $account = new Account($id);
    }
    catch(Exception $e){
        $e->getMessage();
    }
}

class a2{
    function just($id){
    try {
        $account = new Account($id);
    }
    catch(Exception $e){
        $e->getMessage();
    }
}

option2:在 __construct 中捕获异常

class Account{
    function __construct($id){
    try{
        if(empty($id)){
            throw new My_Exception('id can\'t be empty');
        }

        // ...
    }
    catch(My_Exception $e) {

    }
}

请写下在哪些情况下应该使用option1,在哪些情况下应该使用option2或其他更好的解决方案。

谢谢

【问题讨论】:

标签: php exception exception-handling


【解决方案1】:

当然,你应该处理这个函数之外的函数中抛出的异常,否则它没有任何意义。具体就构造函数而言,尽量避免使用“新类名”,而是坚持使用生成器函数。对于每个类 X,决定哪个类负责创建类 X 的对象,并向该类添加一个生成器函数。这个生成器函数也是处理 X 的构造函数异常的理想场所

 class AccountManager {
     function newAccount($id) {
        try {
           $obj = new Account($id);
        } catch....
           return null;
      }
 }

 // all other code uses this instead of "new Account"

 $account = $accountManager->newAccount($id);

【讨论】:

    【解决方案2】:

    抛出异常并立即捕获它的目的是什么?如果你想在出错时中止函数但不抛出错误,你应该return

    因此,您的第一个代码始终是正确的。让异常冒泡。

    【讨论】:

    • 你不能在 PHP 的构造函数中 return
    • @DavidScherer 可以返回,只是不要返回值(return;)。
    • 我知道你可以返回,但返回一个值不会做任何事情(除非你直接调用构造函数,PHP 允许这样做,这鼓励了一些糟糕的编程)。我错误地将您的答案读作建议返回错误而不是抛出它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多