try语句的可选else子句的预期用途是什么?
当前回答
可以在finally子句中以通用的方式使用此构造来处理异常,而在没有异常时执行其他操作:
class TooManyRetries(RuntimeError):
pass
n_tries = 0
max_retries = 2
while True:
try:
n_tries += 1
if n_tries >= max_retries:
raise TooManyRetries
fail_prone_operation()
except Exception1 as ex:
# handle1
except Exception2 as ex:
# handle2
except Exception3 as ex:
# handle3
except TooManyRetries as ex:
raise
else: # No exception
n_tries = 0
finally:
common_restore_state()
continue
其他回答
我能想到的一种使用场景是不可预测的异常,如果您再次尝试,可以避免这种异常。例如,当try块中的操作涉及随机数时:
while True:
try:
r = random.random()
some_operation_that_fails_for_specific_r(r)
except Exception:
continue
else:
break
但是如果可以预测异常,则应该始终在异常之前选择验证。然而,并不是所有的事情都可以预测,所以这种代码模式有它的一席之地。
如果执行落在try的底部(如果没有异常),else块中的语句将被执行。说实话,我从来没有找到过需要。
然而,处理异常注意到:
使用else子句更好 而不是向try中添加额外的代码 因为它避免意外 捕获非异常 由被保护的代码引发 尝试…除了声明。
因此,如果你有一个方法,例如,抛出一个IOError,你想捕捉它引发的异常,但如果第一个操作成功,你还想做其他事情,而你不想从那个操作中捕获IOError,你可能会写这样的东西:
try:
operation_that_can_throw_ioerror()
except IOError:
handle_the_exception_somehow()
else:
# we don't want to catch the IOError if it's raised
another_operation_that_can_throw_ioerror()
finally:
something_we_always_need_to_do()
如果您只是在operation_that_can_throw_ioerror()后面加上另一个other_operation_that_can_throw_ioerror(), except将捕获第二次调用的错误。如果你把它放在整个try块之后,它会一直运行,直到finally之后。else可以让你确定
第二次操作只有在没有例外的情况下才会进行, 它在最后一个块之前运行,并且 它引发的任何ioerror都不会在这里被捕获
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/
我将添加另一个用例,在处理DB会话时看起来很直接:
# getting a DB connection
conn = db.engine.connect()
# and binding to a DB session
session = db.get_session(bind=conn)
try:
# we build the query to DB
q = session.query(MyTable).filter(MyTable.col1 == 'query_val')
# i.e retrieve one row
data_set = q.one_or_none()
# return results
return [{'col1': data_set.col1, 'col2': data_set.col2, ...}]
except:
# here we make sure to rollback the transaction,
# handy when we update stuff into DB
session.rollback()
raise
else:
# when no errors then we can commit DB changes
session.commit()
finally:
# and finally we can close the session
session.close()
查看Python引用,当没有异常时,else似乎在try之后执行。 当控制流出try子句的末尾时,执行可选的else子句。else子句中的异常不由前面的except子句处理。
Dive into python有一个例子,如果我理解正确的话,在try块中他们尝试导入一个模块,当失败时,你会得到异常并绑定默认值,但当它工作时,你可以选择进入else块并绑定所需的内容(参见示例和解释链接)。
如果你试图在catch块中工作,它可能会抛出另一个异常——我想这就是else块派上用场的地方。
推荐文章
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 当使用代码存储库时,如何引用资源的相对路径
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Visual Studio:如何打破处理异常?
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报