Failed to catch syntax error python
You can only catch SyntaxError
if it's thrown out of an eval
, exec
, or import
operation.
>>> try:
... eval('x === x')
... except SyntaxError:
... print "You cannot do that"
...
You cannot do that
This is because, normally, the interpreter parses the entire file before executing any of it, so it detects the syntax error before the try
statement is executed. If you use eval
or its friends to cause more code to be parsed during the execution of the program, though, then you can catch it.
I'm pretty sure this is in the official manual somewhere, but I can't find it right now.
Why can't SyntaxError be caught by user code?
SyntaxError is thrown before the code is actually run. In particular your error handlers haven't been created executed yet.
(You will notice that if you have anything that generate output in your code, such as print statements, the output will not be generated when there's a problem with the syntax, no matter where they are in the code).
However in the use case you described, I don't really see why you would need to catch SyntaxError. It seems to me that you would want to catch errors that depend on the program's state. SyntaxError don't pop up unexpected. If you were able to run your programs once, you will not a SyntaxError in later invocations (unless, of course, you change the code).
Catching SyntaxError
As the documentation says:
This may occur in an import statement, in an exec statement, in a call to the built-in function eval() or input(), or when reading the initial script or standard input (also interactively).
The syntax of the entire file is parsed when your program is read, before any of your code is executed. Python can't even begin to run the code if the syntax is invalid. So you can't catch a SyntaxError that occurs inside your module.
For this particular case, there is an alternative, namely from __future__ import print_function
.
python - catching unfinished string Syntax Error using try except
The reason you can not use a try/except block to capture SyntaxErrors is that these errors happen before your code executes.
High level steps of Python code execution
- Python interpreter translates the Python code into executable instructions. (Syntax Error Raised)
- Instructions are executed. (Try/Except block executed)
Since the error happens during step 1 you can not use a try/except to intercept them since it is only executed in step 2.
How to catch a SyntaxError when f-strings are implemented - when obsolete python is used
It looks like all you want to do on pre-3.6 versions is report an error and terminate the program, and you just want a more user-friendly error message than a SyntaxError stack trace. In that case, instead of trying to catch a SyntaxError, have an entry point file that doesn't use f-strings, and do the version check there, before loading any code that uses f-strings:
# entry point
import sys
if sys.version_info < (3, 6):
# report error, terminate program
else:
import whatever
whatever.main()
python/Django syntax error in Exception handling
codes below are true:
cmd = request.POST.get('command', '')
try:
netconnect = ConnectHandler(**devices)
except Exception as e:
print ('Authentication failed' + ipInsert)
continue
getIP = netconnect.send_command(ipInsert)
Related Topics
Can Existing Virtualenv Be Upgraded Gracefully
Why Use Abstract Base Classes in Python
How to Do Assignments in a List Comprehension
Retrieving a Foreign Key Value with Django-Rest-Framework Serializers
How to Terminate a Thread When Main Program Ends
Convert Floating Point Number to a Certain Precision, and Then Copy to String
How to Get the Largest Integer One Can Use in Python
How to Do a Not Equal in Django Queryset Filtering
What Is the Time Complexity of Popping Elements from List in Python
Checking If All Elements in a List Are Unique
Python Beautifulsoup Extract Text Between Element
Global Variable from a Different File Python
How to Specify an Authenticated Proxy for a Python Http Connection
How to Prevent Python's Urllib(2) from Following a Redirect
How to Run All Python Unit Tests in a Directory
Pyserial Non-Blocking Read Loop
What's the Best Way to Generate a Uml Diagram from Python Source Code