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
Yosef source
share