Aquí todo el mundo debe conocer los 'o' statemens, generalmente pegados a un troquel() comando:PHP: la instrucción 'o' en la instrucción falla: ¿cómo lanzar una nueva excepción?
$foo = bar() or die('Error: bar function return false.');
La mayoría de las veces vemos algo como:
mysql_query('SELECT ...') or die('Error in during the query');
Sin embargo, no puedo entender cómo funciona exactamente esa declaración 'o'.
me gustaría lanzar una nueva excepción en lugar de die(), pero:
try{
$foo = bar() or throw new Exception('We have a problem here');
no funciona, y tampoco
$foo = bar() or function(){ throw new Exception('We have a problem here'); }
La única manera que he encontrado para hacerlo es este horrible pensamiento:
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();
}
¿Pero hay una manera de lanzar una nueva excepción directamente después de la declaración 'o'?
O este tipo de estructura es obligatoria (i no liek la función ThrowMe en absoluto):
try{
$foo = bar();
if(!$foo){
throw new Exception('We have a problem in here');
}
}catch(Exception $e){
echo $e->getMessage();
}
Editar: lo que quiero es realmente para evitar el uso de un if() comprobar cada potencial operación peligrosa que hago, por ejemplo:
#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.
¿Se refiere a '$ foo' en su último bloque de código? –
Lo siento, sí ... mi mal – Strae