如何在构造中以最佳方式处理异常?
选项 1 - 在创建对象时捕获异常:
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();
}
}
选项 2:在 __construct 中捕获异常
class Account{
function __construct($id){
try{
if(empty($id)){
throw new My_Exception('id can\'t be empty');
}
// ...
}
catch(My_Exception $e) {
}
}
请写出在什么情况下应该使用 option1,在什么情况下应该使用 option2 或其他更好的解决方案。
谢谢
最佳答案
当然,你应该在这个函数之外处理一个函数抛出的异常,否则就没有任何意义。特别是关于构造函数,尽量避免使用“新类名”,而是坚持使用生成器函数。对于每个类 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);
关于php - 如何最好地处理构造函数中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3646157/