que*_*sis 1 python exception-handling python-2.7
from __future__ import print_function
try:
print "a"
except SyntaxError:
print('error')
Run Code Online (Sandbox Code Playgroud)
为什么SyntaxError异常没有被抓住?我使用的是Python 2.7
输出:
File "test", line 4
print "a"
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
您无法捕获模块本身的语法错误,因为它在代码运行之前被抛出.Python不会运行代码,因为它是逐行编译的,它是整个文件在这里失败了.
你可以这样做:
syntaxerror.py
from __future__ import print_function
print "a"
Run Code Online (Sandbox Code Playgroud)
catching.py:
from __future__ import print_function
try:
import syntaxerror
except SyntaxError:
print('Error')
Run Code Online (Sandbox Code Playgroud)
因为catching脚本可以在编译后运行,但是尝试导入syntaxerror然后触发新的编译任务syntaxerror.py,引发一个SyntaxError异常然后可以被捕获.
| 归档时间: |
|
| 查看次数: |
183 次 |
| 最近记录: |