PHP:'or'指令失败的语句:如何抛出新的异常?
2022-08-30 19:44:26
这里的每个人都应该知道“or”statemens,通常粘在die()命令上:
$foo = bar() or die('Error: bar function return false.');
大多数时候,我们看到这样的东西:
mysql_query('SELECT ...') or die('Error in during the query');
但是,我无法理解“or”语句究竟是如何工作的。
我想抛出一个新的异常而不是die(),但是:
try{
$foo = bar() or throw new Exception('We have a problem here');
不起作用,两者都不起作用
$foo = bar() or function(){ throw new Exception('We have a problem here'); }
我发现的唯一方法是这个可怕的想法:
function ThrowMe($mess, $code){
throw new Exception($mess, $code);
}
try{
$foo = bar() or ThrowMe('We have a problem in here', 666);
}catch(Exception $e){
echo $e->getMessage();
}
但是有一种方法可以直接在“or”语句之后抛出新的异常?
或者这种结构是强制性的(我根本不喜欢ThrowMe函数):
try{
$foo = bar();
if(!$foo){
throw new Exception('We have a problem in here');
}
}catch(Exception $e){
echo $e->getMessage();
}
编辑:我想要的是真正避免使用if()检查我所做的每个潜在的危险操作,例如:
#The echo $e->getMessage(); is just an example, in real life this have no sense!
try{
$foo = bar();
if(!$foo){
throw new Exception('Problems with bar()');
}
$aa = bb($foo);
if(!$aa){
throw new Exception('Problems with bb()');
}
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#But i relly prefer to use something like:
try{
$foo = bar() or throw new Exception('Problems with bar()');
$aa = bb($foo) or throw new Exception('Problems with bb()');
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#Actually, the only way i figured out is:
try{
$foo = bar() or throw new ThrowMe('Problems with bar()', 1);
$aa = bb($foo) or throw new ThrowMe('Problems with bb()', 2);
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#But i'll love to thro the exception directly instead of trick it with ThrowMe function.