PHP Exception handling

Associate
Joined
1 Feb 2006
Posts
1,868
Location
Reading
Can someone tell me why the most simple code (below) throws

Parse error: syntax error, unexpected '{' on line 2

WTF?

I checked some very similar code on another website on the same hosting package and it is now throwing the error aswell! Only thing i can think of is Vidahost recently upgraded to php 5, but the try statement still exists in php 5. This is infuriating me, it's so stupid!

PHP:
<?php
try{
    $conn=$dbh=mysql_connect ("localhost", "", "");// or die ('Cannot connect to the database because: ' . mysql_error());
    mysql_select_db("kimmystr_wordpress");// or die('Could not select database ');
    $pauthor=$_POST["author"];
    $pcontent=$_POST["comment"];
    $result = mysql_query("insert into wp_comments(comment_author, comment_date, comment_content) values('$pauthor', now(), '$pcontent')");// or die('Fail');
    header('Location: http://www.kimmystravels.co.uk/wp-content/themes/main/messages.php?result=success');
  }
  catch (Exception $e) {
    header('Location: http://www.kimmystravels.co.uk/wp-content/themes/main/messages.php?result=fail');
  }
?>
 
Ran it on my server and it works fine too. Obviously, couldn't connect to the database though.

Strange.

Jon
 
Check you are actually running PHP5. Most hosts when they upgrade, give you the option to either running so run a page with just <?php phpinfo(); ?> in and see what the version number is.
 
Thanks guys, I thought try except had been in php for awhile, silly me.

Strange as I'm sure it worked on my other site without "enabling" it.
 
Out of curiosity.. exactly where is the exception you are going to catch thrown?

and if you are using or die();, why catch in the first place?
 
Out of curiosity.. exactly where is the exception you are going to catch thrown?

and if you are using or die();, why catch in the first place?

I just noticed that. Surely that would cause a fatal error because there's no exception thrown in the try block.

Code:
try {
  if ($var === false) {
    Throw new exception('OMGZ, noob - error!');
  }
} catch(Exception $e) {
  die($e->getMessage());
}

that's how I do it. I was always under the impression that a caught exception would halt everything but it's never seemed to, so I put die() in my exception catching and it works how I want it to. I only ever use exceptions on low-level stuff anyway, though, mainly for development.
 
If you're using the .php extension then the script is certainly running under PHP 4 - depending on which server you're on, renaming the file to .php5 should work.

If it doesn't....you'll be on PHP 5 soon since the only server not running PHP 4 & 5 is only running PHP 4 temporarily :)
 
Back
Top Bottom