【发布时间】:2021-10-04 05:01:02
【问题描述】:
在 Robert Smallshire 和 Austin Bingham 写的非常棒的书中,有以下代码:
def convert(s):
"""Convert a string to an integer."""
try:
return int(s)
except (ValueError, TypeError) as e:
print("Conversion error: {}".format(str(e)), file=sys.stderr)
raise
之后,作者又包含了如下的string_log函数
def string_log(s):
v = convert(s)
return log(v)
string_log('ouch') 的输出如下
我无法理解 raise 语句的确切作用?
另外,作者说在ValueError和TypeError的情况下,第一个函数输出负错误代码-1的代码,即第一个函数如下
import sys
def convert(s):
"""Convert a string to an integer."""
try:
return int(s)
except (ValueError, TypeError) as e:
print("Conversion error: {}".format(str(e)), file=sys.stderr)
return -1
如果我们运行以下命令(没有进行任何更改 string_log())是
string_log('cat')
是非pythonic,但为什么呢?
【问题讨论】:
-
请修正你的缩进。
-
本书的书名(“The Python Apprentice”?)会比您的评论有用得多。
-
您是在问没有参数的
raise做什么,还是在问为什么引发异常优于返回特殊值? -
这能回答你的问题吗? raise with no argument