According to the Python documentation, there are two types or errors:
Syntax errors occur during the parsing time (at the moment your code does not execute , so you have no way to catch errors, because the syntax time is not the execution time when your code actually runs).
The only way to catch syntax errors is when they occur inside a piece of code specified as an argument to the exec function (a python code line is executed):
>>> try: ... exec('x===6') ... except SyntaxError: ... print('Hello!') ... Hello!
But you should remember that you use exec () only when you really know what you are doing. It is not recommended to use exec () at all, especially if it depends on user input.
source share