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

2024-09-24 22:25:51 发布

您现在位置: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)

Tags: 字符串程序消息byifdefnot数字
1条回答
网友
1楼 · 发布于 2024-09-24 22:25:51

如果尝试用字符串除,则得到一个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:`

相关问题 更多 >