0

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.

Atena Dadkhah
  • 623
  • 1
  • 5
  • 19

2 Answers2

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.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33
  • This was the problem. I loaded the code in notepad and specifically made sure that everything that should be a space was a space (although I thought I originally coded it manually anyway). But now it works. Thank you very much! – benjamin63 Jan 04 '23 at 09:38
0
echo 'Caught exception: ', $ex->getMessage(); 

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

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