我怎么能写一个尝试/except块捕获所有异常?
当前回答
有多种方法可以做到这一点,特别是在Python 3.0及以上版本中
方法1
这是一种简单的方法,但不推荐使用,因为你不知道到底是哪行代码引发了异常:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
方法2
推荐使用这种方法,因为它提供了关于每个异常的更多细节。它包括:
代码的行号 文件名称 更详细地描述实际错误
唯一的缺点是需要导入tracback。
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
其他回答
我刚刚发现了在Python 2.7中测试if异常名称的小技巧。有时我在代码中处理了特定的异常,所以我需要一个测试,看看这个名字是否在处理的异常列表中。
try:
raise IndexError #as test error
except Exception as e:
excepName = type(e).__name__ # returns the name of the exception
你可以,但你可能不应该:
try:
do_something()
except:
print("Caught it!")
然而,这也会捕获像KeyboardInterrupt这样的异常,你通常不希望那样,对吗?除非你马上重新抛出异常-请参阅下面的文档示例:
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print("I/O error({0}): {1}".format(errno, strerror))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
有多种方法可以做到这一点,特别是在Python 3.0及以上版本中
方法1
这是一种简单的方法,但不推荐使用,因为你不知道到底是哪行代码引发了异常:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
方法2
推荐使用这种方法,因为它提供了关于每个异常的更多细节。它包括:
代码的行号 文件名称 更详细地描述实际错误
唯一的缺点是需要导入tracback。
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
您可以这样做来处理一般异常
try:
a = 2/0
except Exception as e:
print e.__doc__
print e.message
要捕获所有可能的异常,请捕获BaseException。它位于Exception层次结构的顶部:
Python 3: https://docs.python.org/3.10/library/exceptions.html#exception-hierarchy
Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy
try:
something()
except BaseException as error:
print('An exception occurred: {}'.format(error))
但正如其他人提到的,你通常不需要这个,只有在非常特定的情况下。
推荐文章
- Visual Studio Code:如何调试Python脚本的参数
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc
- 结合conda环境。Yml和PIP requirements.txt
- 将命名元组转换为字典
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件
- 在Python中,使用argparse只允许正整数
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum