Try-Catch Syntax Weirdness

Posted by Tim Koschützki, on Jun 21, 2007 - in PHP & CakePHP » Other

Deprecated post

The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.

Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.

Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).

I just noticed today, that PHP's try catch blocks require curly braces. So the following will output a parse error:

php
  1. try {
  2.     $error = 'Throw this error';
  3.     throw new Exception($error);
  4.  
  5.     echo 'Never get here';
  6.  
  7. } catch (Exception $e)
  8.     echo 'Exception caught: ',  $e->getMessage(), "\n";

Anybody has an idea why it is like that? I have used curly braces by default up until now, so I just stumbled upon this weirdness today. This here works perfectly:

php
  1. try {
  2.     $error = 'Throw this error';
  3.     throw new Exception($error);
  4.  
  5.     echo 'Never get here';
  6.  
  7. } catch (Exception $e) {
  8.     echo 'Exception caught: ',  $e->getMessage(), "\n";
  9. }

I always use curly braces by default and just seemed to have forgotten about them for a moment today. *shrug*