What is the best way to handle exceptions in the constructor?

What is the best way to handle an exception in a constructor?

option1 - catch exception where the object was 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 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) {

    }
}

Please write in which cases option1 should be used and in which option2 or another best solution should be used.

thank

+3
source share
2 answers

, , , . , " " . 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);
+6

? , , return.

, . .

+6

Source: https://habr.com/ru/post/1763323/


All Articles