... or throw Exception

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
andre_c
Forum Contributor
Posts: 412
Joined: Sun Feb 29, 2004 6:49 pm
Location: Salt Lake City, Utah

... or throw Exception

Post by andre_c »

Does anyone know why this code throws a parse error?

Code: Select all

<?
$query = mysql_query( $query ) or throw new Exception( mysql_error() );
?>
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Post by d3ad1ysp0rk »

Could you.. possibly post the error?

Also, are you by chance running php4?
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Re: ... or throw Exception

Post by infolock »

andre_c wrote:Does anyone know why this code throws a parse error?

Code: Select all

<?
$query = mysql_query( $query ) or throw new Exception( mysql_error() );
?>

#1, $query is set to nothing...
#2, why not do it like this

Code: Select all

$result=mysql_query($query) or die(MySQL_Error());
User avatar
andre_c
Forum Contributor
Posts: 412
Joined: Sun Feb 29, 2004 6:49 pm
Location: Salt Lake City, Utah

Post by andre_c »

sorry, i should have been more specific:
It's php 5 and the $query variable is a string with a valid sql statement (irrelevant, since it's giving me a parse error, not a fatal error or warning)

Code: Select all

Parse error: parse error, unexpected T_THROW in /www/youcaneauction.com/classes/Site.class.php on line 383
and i don't want to use ' or die( mysql_error() )' because it will only give me the mysql error, while throwing the exception will give me a stack trace.
Also i much rather catch the exception higher in the program hierarchy than kill the script because of a bad sql query

[edited] I am guessing that since a throw statement doesn't evaluate to true or false like functions do, it cannot be placed after a logical operator[/edited]
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

so you could rewrite the code as

Code: Select all

$result = mysql_query($query);
if (!$result)
{
    throw new Exception(mysql_error());
}
User avatar
andre_c
Forum Contributor
Posts: 412
Joined: Sun Feb 29, 2004 6:49 pm
Location: Salt Lake City, Utah

Post by andre_c »

thanks, that's exactly what i ended up doing
Post Reply