未捕获Python语法错误 [英] Python Syntax Error is not being caught

查看:136
本文介绍了未捕获Python语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from __future__ import print_function

try:
    print "a"
except SyntaxError:
    print('error')

为什么没有 SyntaxError 异常抓住?我正在使用Python 2.7

Why is the SyntaxError exception not being caught? I am using Python 2.7

输出:

  File "test", line 4
    print "a"
            ^
SyntaxError: invalid syntax


推荐答案

您无法在模块本身中捕获语法错误,因为该错误是在代码运行之前抛出的。 Python不会运行代码,因为它是逐行编译的,这是整个文件在这里失败。

You cannot catch the syntax error in the module itself, because it is thrown before the code is run. Python doesn't run the code as it is compiled line by line, it is the whole file that failed here.

您可以执行此操作:

syntaxerror.py

from __future__ import print_function

print "a"

catching.py

from __future__ import print_function

try:
    import syntaxerror
except SyntaxError:
    print('Error')

因为捕获脚本可以在编译后运行,但是尝试导入语法错误,然后在 syntaxerror.py 上触发新的编译任务,引发 SyntaxError 异常,然后可以将其捕获。

because the catching script can be run after compiling, but trying to import syntaxerror then triggers a new compilation task on syntaxerror.py, raising a SyntaxError exception which then can be caught.

这篇关于未捕获Python语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆