try语句的可选else子句的预期用途是什么?
当前回答
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/
其他回答
下面是我喜欢使用这种模式的另一个地方:
while data in items:
try
data = json.loads(data)
except ValueError as e:
log error
else:
# work on the `data`
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!
我发现其他有用的处理可能不正确的配置文件:
try:
value, unit = cfg['lock'].split()
except ValueError:
msg = 'lock monitoring config must consist of two words separated by white space'
self.log('warn', msg)
else:
# get on with lock monitoring if config is ok
读取锁配置的异常禁用锁监控,ValueErrors记录有用的警告消息。
错误和异常#处理异常- docs.python.org
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.
PEP 380中有一个很好的try-else示例。基本上,它归结为在算法的不同部分做不同的异常处理。
大概是这样的:
try:
do_init_stuff()
except:
handle_init_suff_execption()
else:
try:
do_middle_stuff()
except:
handle_middle_stuff_exception()
这允许您在异常发生的地方编写异常处理代码。
推荐文章
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 当使用代码存储库时,如何引用资源的相对路径
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Visual Studio:如何打破处理异常?
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴