使用try时是否可能有多个Python除外语句(无需搜索特定的除外)?
作者:互联网
这是我当前的代码:
def get_queryset(self)
pk = self.kwargs['pk']
try:
postD = PostD.objects.get(pk=pk)
# In the line below, PostReply.objects.filter(postD=postD) is
# not guaranteed to exist, so I am using a try statement.
return PostReply.objects.filter(postD=postD)
except:
postY = PostY.objects.get(pk=pk)
# In the line below, PostReply.objects.filter(postY=postY) is
# not guaranteed to exist either, so this may raise an error.
return PostReply.objects.filter(postY=postY)
# Here, I want one last except statement to execute if the above try
# and except statements fail... Is it okay to just add another except
# statement like this:
except:
postR = PostR.objects.get(pk=pk)
# If the above try and except statement fail, this is guaranteed to
# not throw an error.
return PostReply.objects.filter(postR=postR)
我知道我可以做这样的事情:
try:
# code
except ObjectDoesNotExist:
# code
except:
# last part of code
但不能保证我会遇到ObjectDoesNotExist错误(我不能保证会得到什么错误).因此,我想知道是否有一种方法可以拥有一个以上的except语句,而无需指定要查找的异常?是我上面做的方式(我只是尝试过:except:except:可以使用吗?
解决方法:
唯一的例外:将捕获所有内容,因此在这种情况下,拥有第二个例外是没有意义的.
可能您想将代码放在第一个except块内,放入另一个嵌套的try / except块中.
注意:Pokemon exception handling被认为是不好的编码风格,最好只尝试捕获要处理的实际异常-在这种情况下,仅捕获DidNotExist就足够了.
您可以考虑使用循环来重构它:
PostModels = {
'postD': PostD,
'postY': PostY,
'postR': PostR,
}
for k,Post in PostModels.items():
try:
post = Post.objects.get(pk=pk)
except Post.DoesNotExist:
pass
else:
return PostReply.objects.filter(k=post)
else:
# all 3 lookups failed, how do you want to handle this?
标签:try-catch,python,django 来源: https://codeday.me/bug/20191027/1945678.html