这是我当前的代码:
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语句而不指定要查找的异常?我上面的方法(我只有try: except: except:
)可以使用吗?你知道吗
由于第一个
except
将捕获从try
块引发的任何异常,因此“上述try和except语句失败”的唯一方法是如果第一个except
块中的代码引发异常。要捕获它,您应该直接用try/except
包装它:另外,一般来说,您应该避免裸
except:
。你知道吗一个空的
except:
将捕获任何东西,因此在本例中,除了块之外,再加一个块是没有意义的。你知道吗可能您想将第一个
except
块中的代码放入另一个嵌套的try/except块中。你知道吗注意:Pokemon exception handling被认为是不好的编码风格,如果您只尝试捕获您想要处理的实际异常就更好了-在这种情况下,只捕获
DoesNotExist
就足够了。你知道吗您可以考虑使用循环来重构:
相关问题 更多 >
编程相关推荐