Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat exceptions in constructor best?

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

like image 320
Ben Avatar asked Sep 05 '10 13:09

Ben


People also ask

How do you handle exceptions in constructor?

When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.

Is it good practice to throw exception in constructor?

Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.

Is it good practice to throw exception in constructor C++?

Yes. That's precisely how a constructor signals that something went wrong and the object could not be constructed properly. A constructor is responsible for completely initializing the object in a valid, usable state. If it can't do this for some reason, there is no way to return a value to the caller.


1 Answers

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);
like image 99
user187291 Avatar answered Oct 20 '22 06:10

user187291