python - 尝试,使用 if 和 else 的 except 子句
问题描述
让我们想象一下这段代码:
try:
if condition1 and condition2: # some_exception may happen here
function1()
elif condition3 and condition4: # some_exception may happen here
function2()
else:
big
block
of
instructions
except some_exception:
big
block
of
instructions
正如你所看到的,我重复了大量的指令(两者都是相同的)。有没有办法避免重复,但与将代码放在函数中不同?
某种不同的逻辑或使用 finally 或 else 来尝试?我就是想不通。
提前感谢您帮助我!
解决方案
如果你不喜欢使用函数,那么在两个地方都设置一个变量,然后再检查呢?
像这样的东西:
do_stuff = False
try:
if condition1 and condition2: # some_exception may happen here
function1()
elif condition3 and condition4: # some_exception may happen here
function2()
else:
do_stuff = True
except some_exception:
do_stuff = True
...
if do_stuff:
big
block
of
instructions
推荐阅读
- c++ - 使用二进制文件的用户名和登录系统
- android - 无法获取 note.dit-inc.us/down.html android studio
- html - 将 ':focus' 样式应用于输入组
- c# - 即使当前视图和其他视图已显示,也无法找到视图
- java - bean 构造函数中的 Java 值注入
- python - python请求中找不到404的解决方案吗?
- salesforce - 在我的单元测试期间,断言语句在测试类中失败
- php - axios.delete 的“尝试获取非对象的属性‘参数’”。后端:PHP 前端:React
- angular - 角度数据未定义
- scala - 如何处理在scala中解析json的异常