相关疑难解决方法(0)

在python中使用try vs if

在测试变量有值时,是否有理由决定使用哪一个try或哪些if结构?

例如,有一个函数返回列表或不返回值.我想在处理之前检查结果.以下哪一项更可取,为什么?

result = function();
if (result):
    for r in result:
        #process items
Run Code Online (Sandbox Code Playgroud)

要么

result = function();
try:
    for r in result:
        #process items
except TypeError:
    pass;
Run Code Online (Sandbox Code Playgroud)

相关讨论:

检查Python中的成员是否存在

python

120
推荐指数
5
解决办法
5万
查看次数

条件检查与异常处理

什么时候异常处理比条件检查更可取?在很多情况下我可以选择使用其中一种.

例如,这是一个使用自定义异常的求和函数:

# module mylibrary 
class WrongSummand(Exception):
    pass

def sum_(a, b):
    """ returns the sum of two summands of the same type """
    if type(a) != type(b):
        raise WrongSummand("given arguments are not of the same type")
    return a + b


# module application using mylibrary
from mylibrary import sum_, WrongSummand

try:
    print sum_("A", 5)
except WrongSummand:
    print "wrong arguments"
Run Code Online (Sandbox Code Playgroud)

这是相同的功能,避免使用异常

# module mylibrary
def sum_(a, b):
    """ returns the sum of two summands if they are both of the same …
Run Code Online (Sandbox Code Playgroud)

python error-handling exception conditional-statements

16
推荐指数
2
解决办法
2844
查看次数