Php: 'Or' Statement on Instruction Fail: How to Throw a New Exception

PHP: 'or' statement on instruction fail: how to throw a new exception?

or is just a logical operator, and it's analogous to ||.

The common trick of

mysql_query() or die();

could just as well be written

mysql_query() || die();

What happens here is the "logical or" operator (whichever you choose) is trying to determine if either operand evaluates to TRUE. This means the operands must be expressions that can be cast as a boolean.

So, the reason

bar() or throw new Exception();

is illegal, is because

(boolean)throw new Exception();

is also illegal. In essence, the process of throwing an exception doesn't generate a return value for the operator to check.

But calling a function does generate a return value for the operator to check (no explicit return value will result int the function returning NULL which casts as FALSE) which is why it works for you when you wrap exception throwing in a function.

PHP old-school function or with exception

Do it the less "clever" way:

if(!foo()) {
throw new Exception('AHH!');
}

In case you're wondering why or throw new Exception() doesn't work, it's because you're relying on the short-circuiting of the or operator: If the first argument is true, then there's no need to evaluate the second to determine if one of them is true (since you already know that at least one of them is true).

You can't do this with throw since it's an expression that doesn't return a boolean value (or any value at all), so oring doesn't make any sense.

If you really want to do this, the deleted answer by @emie should work (make a function that just throws an exception), since even a function with no return value is valid in a boolean statement, but it seems like a bad idea to create a function like that just so you can do clever things with boolean statements.

Why is it that throw new exception does not echo the message?

Should be like this

function searchMovie($movieName){
if (!isset($movieName))
{
throw new Exception('missing movie name');
//execute
//return something here
}
}

PHP rename() doesn't throws exception on error

"Normal" PHP functions don't throw exceptions.

Change your code to simulate an exception:

try{
if(rename($archivo_salida, $ruta_archivos)){
//anything;
} else {
throw new Exception('Can not rename file'.$archivo_salida);
}
}catch (Exception $e)
//do something
}

PDO Insert Should Throw Exception, But Doesn't

2 points.

First is pointed by @Funk Forty Niner. By default PDO send warning, not exception. You must set the error mode :

$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

Second: use the "named parameters" not the "columns name" for the array in your execute method

$statement->execute([
':requestor' => $requestor_id,
':location' => $request_location
]);

Can I use an exception with a database query?

This is the way I normally do it. I have my database in a wrapper class, so $this simply refers to the wrapper.

private function throwException($query = null)
{
$msg = mysql_error().". Query was:\n\n".$query.
"\n\nError number: ".mysql_errno();
throw new Exception($msg);
}

public function query($query_string)
{
$this->queryId = mysql_query($query_string);
if (! $this->queryId) {
$this->throwException($query_string);
}
return $this->queryId;
}

That packages it all up with a nice error message for me, so I can see the problem query. You could keep it much simpler of course, and do:

mysql_query($sql) or throw new Exception("Problem with query: ".$sql);

PHP exception is caught, but error message still appears

When you try/catch() a block of code then you wont get a fatal error of "Uncaught exception". A fatal error will cause the script to stop executing at the point of the error. Since you caught the exception, it did what you told it to: Echo the string + error message, then it continued execution to "Hello World!". If anything your error reporting is more verbose due to your INI settings, like the stack trace printout.

PHP try/catch and fatal error

try/catch blocks only work for thrown exceptions (throw Exception or a subclass of Exception must be called). You cannot catch fatal errors using try/catch.

If your DB connection cannot be established, I would consider it fatal since you probably need your DB to do anything meaningful on the page.

PDO will throw an exception if the connection cannot be established. Your specific problem is that $db is not defined when you try to call a method with it so you get a null pointer (sort of) which is fatal. Rather than jump through if ($db == null) hoops as others are suggesting, you should just fix your code to make sure that $db is either always defined when you need it or have a less fragile way of making sure a DB connection is available in the code that uses it.

If you really want to "catch" fatal errors, use set_error_handler, but this still stops script execution on fatal errors.

Is 'or' treated as a boolean check on the return of a statement?

In your case, they are exactly the same because of short circuit evaluation, however if null or some other falsey vale is returned, it will make a difference. Note:

function f(){return false;} 
function w(){return "w";}
$a = f() or w();
echo isset($a);
// 1 (true). $a === FALSE!

Now, note what happens with a lack of a return:

function f(){} 
function w(){return "w";}
$a = f() or w();
echo isset($a);
// nothing (false)


Related Topics



Leave a reply



Submit