欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

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

发布时间:2023/12/4 python 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python让函数抛出异常,是否有任何对象可以使str()函数在python中抛出错误或异常?... 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

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

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

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

总结

以上是生活随笔为你收集整理的python让函数抛出异常,是否有任何对象可以使str()函数在python中抛出错误或异常?...的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。