如何最好地处理构造函数中的异常?

Yos*_*sef 4 php exception-handling exception

如何在构造中以最佳方式对待异常?

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

option2:在__construct中捕获异常

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

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

    }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Nik*_*kiC 7

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

因此,您的第一个代码始终是正确的.让异常泡沫起来.


use*_*291 6

当然,你应该处理在这个函数之外的函数中引发的异常,否则它将没有任何意义.关于构造函数,尽量避免使用"新类名",而是坚持使用生成器函数.对于每个类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);
Run Code Online (Sandbox Code Playgroud)