How to treat exceptions in constructor best?

前端 未结 2 655
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 03:50

How to treat exception in best way in construct?

option1 - catch exception where object created:

class Account {
    function __cons         


        
2条回答
  •  被撕碎了的回忆
    2021-01-03 04:20

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

提交回复
热议问题