php - How to treat exceptions in constructor best?

494

How to treat exception in best way in construct?

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 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 should be used option1 and in which should be used option2 or other better solution.

Thanks

783

Answer

Solution:

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

Answer

Solution:

What is the purpose of throwing an exception and immediately catching it? If you want to abort a function on error but not throw an error, you shouldreturn.

Thus, your first code is always correct. Let the Exception bubble up.

People are also looking for solutions to the problem: php - Related Questions Algorithm

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.