简体   繁体   中英

python - catching unfinished string Syntax Error using try except

I am new to python and I had no difficulty with one example of learning try and except blocks:

try:
    2 + "s"
except TypeError:
    print "There was a type error!"

Which outputs what one would expect:

There was a type error!

However, when trying to catch a syntax error like this:

try:
    print 'Hello
except SyntaxError:
    print "There was a syntax error!"
finally:
    print "Finally, this was printed"

I would ironically get the EOL syntax error. I was trying this a few times in the jupyter notebook environment and only when I moved over to a terminal in VIM did it make sense to me that the compiler was interpreting the except and finally code blocks as the rest of the incomplete string.

My question is how would one go about syntax error handling in this format? Or is there a more efficient (pythonic?) way of going about this?

It might not be something that one really comes across but it would be interesting to know if there was a clean workaround.

Thanks!

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

  1. Python interpreter translates the Python code into executable instructions. (Syntax Error Raised)
  2. 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.

The answer is easy cake:

The SyntaxError nullifies the except and finally statement because they are inside of a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM