0

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!

David Tahvildaran
  • 307
  • 1
  • 3
  • 10
  • missing a closing quote after the line: print 'Hello – Azeem Ghumman Jul 19 '17 at 19:07
  • 6
    You can't; such syntax errors are raised during parsing, not execution. The parser doesn't even see that there *is* an `except` statement, because it's still part of the string it is parsing. You get the EOL error because a non-triple-quoted string must be closed before the end of the current line. – chepner Jul 19 '17 at 19:08
  • 2
    The only catchable `SyntaxError`s are the ones raised from within a syntactically valid `exec` statement whose *argument* contains syntax errors. – chepner Jul 19 '17 at 19:10
  • @chepner `exec` or `eval`, possibly also `ast.literal_eval`. – Błotosmętek Jul 19 '17 at 19:15
  • 2
    Possible duplicate of [Failed to catch syntax error python](https://stackoverflow.com/questions/25049498/failed-to-catch-syntax-error-python) – Łukasz Rogalski Jul 19 '17 at 19:33
  • @Błotosmętek I *meant* to say that `exec` was one example of a statement that could raise a catchable `SyntaxError`; apparently, I did *not* :) – chepner Jul 19 '17 at 19:34

2 Answers2

0

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.

Richard Christensen
  • 2,046
  • 17
  • 28
-1

The answer is easy cake:

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

S.G. Harmonia
  • 297
  • 2
  • 18