如何处理最佳构造函数中的异常? [英] How to treat exceptions in constructor best?

查看:115
本文介绍了如何处理最佳构造函数中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to treat exception in best way in construct?

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

option1 - catch exception where object created:

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 :catch异常里面__construct

option2: catch exception inside __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或其他更好的解决方案。

Please write in which cases should be used option1 and in which should be used option2 or other better solution.

谢谢

推荐答案

当然,你应该处理一个抛出的异常在这个功能以外的功能,否则就没有任何意义。对于具体的构造函数,尽量避免新的类名,并且坚持使用生成器函数。对于每个类X,决定哪个类负责创建类X的对象,并向该类添加生成器函数。这个生成函数也是处理X的构造函数异常的完美的地方。

Of course, you should handle an exception thrown in a function outside this function, otherwise it won't make any sense. In regard to constructors specifically, try to avoid "new classname" as much as possible and stick to generator functions instead. For each class X, decide which class is responsible for creating objects of class X, and add a generator function to that class. This generator function is also the perfect place to handle X's constructor exceptions

 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);

这篇关于如何处理最佳构造函数中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆