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.
You won’t be able to directly do
or throw new Exception();becausethrowis a statement, not an expression. Sinceoris really an operator, it expects its operands to be expressions (things that evaluate to some values).You’d have to do this instead:
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 thethrowstatement directly, like this: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
Exceptionclass, 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 theExceptionclass).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().