try语句的可选else子句的预期用途是什么?
当前回答
Python try-else try语句的可选else子句的预期用途是什么?
其预期用途是,如果没有预期要处理的异常,则为运行更多代码提供上下文。
这个上下文避免意外处理您没有预料到的错误。
但是理解导致else子句运行的确切条件非常重要,因为return、continue和break可以中断到else的控制流。
总之
如果没有异常,并且没有被return、continue或break语句中断,else语句将运行。
其他答案忽略了最后一部分。
从文档中可以看出:
类型的控件流出时,执行可选的else子句 try子句结束
(粗体)。脚注写道:
*目前,控制“从末端流出”,除非在 异常或return、continue或break语句的执行。
它至少需要一个except子句(参见语法)。所以它实际上不是“try-else”,而是“try-except-else(-finally)”,其中else(和finally)是可选的。
Python教程详细说明了预期的用法:
The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example: for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.
示例区分else和try块后面的代码
如果处理错误,else块将不会运行。例如:
def handle_error():
try:
raise RuntimeError('oops!')
except RuntimeError as error:
print('handled a RuntimeError, no big deal.')
else:
print('if this prints, we had no error!') # won't print!
print('And now we have left the try block!') # will print!
现在,
>>> handle_error()
handled a RuntimeError, no big deal.
And now we have left the try block!
其他回答
else:块令人困惑并且(几乎)毫无用处。它也是for和while语句的一部分。
实际上,即使在if语句中,else:也可能被滥用,造成非常难以发现的错误。
考虑这一点。
if a < 10:
# condition stated explicitly
elif a > 10 and b < 10:
# condition confusing but at least explicit
else:
# Exactly what is true here?
# Can be hard to reason out what condition is true
三思而后行。这通常是个问题。除非在if语句中,否则避免使用它,即使在if语句中,也要考虑记录else-条件,使其显式。
下面是我喜欢使用这种模式的另一个地方:
while data in items:
try
data = json.loads(data)
except ValueError as e:
log error
else:
# work on the `data`
即使你现在想不出它的用途,你可以打赌它一定会有用处的。下面是一个没有想象力的例子:
其他:
a = [1,2,3]
try:
something = a[2]
except IndexError:
print("out of bounds")
else:
print(something)
没有其他的:
try:
something = a[2]
except IndexError:
print("out of bounds")
if "something" in locals():
print(something)
在这里,如果没有抛出错误,则定义了变量something。您可以在try块之外删除它,但如果定义了变量,则需要进行一些混乱的检测。
try:
statements # statements that can raise exceptions
except:
statements # statements that will be executed to handle exceptions
else:
statements # statements that will be executed if there is no exception
例子:
try:
age=int(input('Enter your age: '))
except:
print ('You have entered an invalid value.')
else:
if age <= 21:
print('You are not allowed to enter, you are too young.')
else:
print('Welcome, you are old enough.')
输出:
>>>
Enter your age: a
You have entered an invalid value.
>>> RESTART
>>>
Enter your age: 25
Welcome, you are old enough.
>>> RESTART
>>>
Enter your age: 13
You are not allowed to enter, you are too young.
>>>
复制自:https://geek-university.com/python/the-try-except-else-statements/
Try-except-else非常适合结合EAFP模式和duck-typing:
try:
cs = x.cleanupSet
except AttributeError:
pass
else:
for v in cs:
v.cleanup()
您可能认为naïve代码是好的:
try:
for v in x.cleanupSet:
v.clenaup()
except AttributeError:
pass
这是在代码中意外隐藏严重错误的好方法。我在那里输入了清理,但是让我知道的AttributeError正在被吞噬。更糟糕的是,如果我写对了,但清理方法偶尔被传递一个具有错误命名属性的用户类型,导致它在中途无声地失败并留下一个未关闭的文件,会怎样?祝你在调试时好运。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象