Home » Php » Is there a static way to throw exception in php

Is there a static way to throw exception in php

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is there a “static” way of throwing an exception in php?

I need to throw an exception when a mysql query fails.

I tried this:

[email protected]_query( $query ) or throw new Exception(' Query Failed ');

but it’s not working.

And I’m using a function based on the throwException() function from this comment at PHP: Exceptions manual, but I would like to know if there is a static way for doing this without making a class.

How to&Answers:

You won’t be able to directly do or throw new Exception(); because throw is a statement, not an expression. Since or is really an operator, it expects its operands to be expressions (things that evaluate to some values).

You’d have to do this instead:

$re = mysql_query($query);

if (!$re) {
    throw new Exception('Query Failed');
}

If you’re trying to use the throwException() function proposed by that PHP manual comment, as webbiedave points out the comment is saying that you need to call that function instead of the throw statement directly, like this:

$re = mysql_query($query) or throwException('Query Failed');

There’s no rule in PHP that says you need to throw exceptions from a class method. As long as there’s some way to catch that exception you’re fine. If you mean you want to throw exceptions without using the Exception class, well, you have to. Exceptions are objects by nature; you can’t throw an exception that isn’t an object (or doesn’t inherit from the Exception class).

If you don’t want to throw exceptions but raise the kind of error you often see from PHP (notices, warnings and fatal errors), use trigger_error().

$re = mysql_query($query);

if (!$re) {
    trigger_error('Query Failed', E_USER_ERROR);
}

Answer:

The comment you link to states that throwing an exception in this way will not work. It states you have to place it in a function:

function throwException($message = null, $code = null) {
    throw new Exception($message, $code);
}

$re = mysql_query($query) or throwException('Query Failed');

Answer:

You might also try something like

mysql_query($query);

if (mysql_error()) {
  throw new Exception(...);
}

as mysql_error() returns empty string if there was no error, which evaluates to false.