如何在 python 中捕获 IndentationError 异常?
每当编译器发现源代码不符合缩进规则时,就会发生缩进错误(IndentationError)。在导入模块时,可以捕获该异常,因为模块将在第一次导入时进行编译。无法在包含 try/except 块的模块中捕获它,因为在出现此异常时,Python 将无法完成编译模块,并且模块中不会运行任何代码。
我们按如下方式重新编写给定代码以处理异常
示例
try: def f(): z=['foo','bar'] for i in z: if i == 'foo': except IndentationError as e: print e
输出
"C:/Users/TutorialsPoint1/~.py", line 5 if i == 'foo': ^ IndentationError: expected an indented block
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP