Is there a static way to throw exception in php

强颜欢笑 提交于 2019-12-23 08:50:23

问题


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:

$re=@mysql_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.


回答1:


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);
}



回答2:


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');



回答3:


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.



来源:https://stackoverflow.com/questions/4905867/is-there-a-static-way-to-throw-exception-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!