skip to Main Content

I have done a lot of PHP coding but never used try/catch before. First time user. It won’t work, does not even compile. I am trying this very simple example.

$x = 0;
try {
    if ($x == 0) {
        throw new Exception('x is zero');
    }
} catch (Exception $ex) {
    echo 'Caught exception: ', $ex->getMessage();
}
echo 'after try block';

When I run this, I get this error message referring to the line with the catch in it.

Parse error: syntax error, unexpected '$ex' (T_VARIABLE), expecting ',' or ')'

Was expecting to get the Caught exception line displayed.

2

Answers


  1. echo 'Caught exception: ', $ex->getMessage(); 
    

    instead of comma, there should be a full stop for string concatenation

    echo 'Caught exception: '. $ex->getMessage(); 
    
    Login or Signup to reply.
  2. I think you copied this from the PHP manual. The manual doesn’t use real spaces in their code. That has tricked me up several times already. See:

    https://3v4l.org/TW2Zr

    Here the fake spaces are shown:


    enter image description here


    You need to make sure you’re using real spaces.

    In some editors you can make these fake spaces visible, and some other editors will already replace them for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search