python让函数抛出异常,是否有任何对象可以使str()函数在python中抛出错误或异常?...

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:42   2040   0

我有一个函数,要求输入是一个字符串.

我知道我可以断言或检查输入类型,但我想尽可能地处理它.

我有以下代码来处理它.但我想知道是否有任何情况,这一行可以抛出我需要处理的异常.

def foo(any_input):

clean_input = str(any_input) # will this throw any exception or error?

process(clean_input)

尝试str深度嵌套列表时,可能会遇到RuntimeError:

>>> x = []

>>> for i in range(100000):

... x = [x]

...

>>> y = str(x)

Traceback (most recent call last):

File "", line 1, in

RuntimeError: maximum recursion depth exceeded while getting the repr of a list

或者一个MemoryError试图查找一个巨大的列表:

>>> x = 'a'*1000000

>>> y = [x] * 1000000 # x and y only require a few MB of memory

>>> str(y) # but str(y) requires about a TB of memory

Traceback (most recent call last):

File "", line 1, in

MemoryError

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP