每个人都应该知道“or”语句,通常与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.
!$foo
? - Dominic Rodger