简体   繁体   English

尝试使用try捕获未完成的字符串语法错误

[英]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: 我是python的新手,我不难举一个学习try的例子,除了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. 具有讽刺意味的是,我会得到EOL语法错误。 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. 我在jupyter笔记本环境中尝试了几次,只有当我移到VIM中的终端时,我才知道编译器将except代码块和最终代码块解释为不完整字符串的其余部分。

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? 还是有一种更有效的方法(pythonic?)来解决这个问题?

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. 您不能使用try / except块捕获SyntaxErrors的原因是这些错误在代码执行之前发生。

High level steps of Python code execution Python代码执行的高级步骤

  1. Python interpreter translates the Python code into executable instructions. Python解释器将Python代码转换为可执行指令。 (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. 由于错误发生在步骤1中,因此您不能使用try / except来拦截它们,因为它仅在步骤2中执行。

The answer is easy cake: 答案很简单:

The SyntaxError nullifies the except and finally statement because they are inside of a string. SyntaxError使exceptfinally语句无效,因为它们位于字符串内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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