Everyone here should know the 'or' statemens, usually glued to an die() command:
$foo = bar() or die('Error: bar function return false.');
The most of the times we see something like:
mysql_query('SELECT ...') or die('Error in during the query');
However, i cant understand how exactly that 'or' statement works.
I would like to throw a new exception instead of die(), but:
try{
$foo = bar() or throw new Exception('We have a problem here');
Doesnt work, and neither
$foo = bar() or function(){ throw new Exception('We have a problem here'); }
The only way i found to do that is this horrible thought:
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();
}
But there is a way to throw a new exception directly after the 'or' statement?
Or this kind of structure is mandatory (i dont liek the ThrowMe function at all):
try{
$foo = bar();
if(!$foo){
throw new Exception('We have a problem in here');
}
}catch(Exception $e){
echo $e->getMessage();
}
Edit: what i want is really to avoid the use of an if() check every potential dangerous operation i do, for example:
#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.
Why don't
bar()
andbb()
throw the exceptions? In PHP Exceptions bubble up, so there's no need to throw the exception in the function/method where you callbar()
/bb()
. These exceptions may be thrown bybar()
/bb()
. In case you want to throw another exception, you can simply do: