如何在python中处理字符串异常

时间:2019-06-13 14:57:13

标签: python

程序使用异常处理查找两个数字的除法。如果我的两个变量之一或两者均为字符串或分母为零,则可能会出现异常。相应地引发异常,并为不同的异常打印不同的消息以捕获异常。

def divide(a, b): 
    try:
        if b.isalpha():
            raise ValueError('dividing by string not possible')
        c= a/b 
        print('Result:', c)
    except ZeroDivisionError: 
        print("dividing by zero not possible ")
divide(3,abc)

1 个答案:

答案 0 :(得分:1)

如果尝试用字符串进行除法,则会得到TypeError。 Python认可“请求宽恕,而不是许可”的方法,因此,如果不检查表达式TypeError,则不必检查表达式是否可以正确解析(作为奖励,这样做还可以解决其他非不适用于除法的数字数据类型。

此外,这也许是您所不知道的,您可以将except子句彼此链接,以捕获同一try块中的不同种类的异常,并以不同的方式处理它们。

示例:

def divide(a, b): 
    try:
        c= a/b 
        print('Result:', c)
    except ZeroDivisionError: 
        print("dividing by zero not possible ")
    except TypeError:
        print("a and b must both be integers")
        # you could do additional checks in here if you wanted to determine which
        #   variable was the one causing the problem, e.g. `if type(a) != int:`