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

如何在python中处理字符串异常,python,Python,通过异常处理查找两个数字的除法的程序。如果我的两个变量中的一个或两个都是字符串或分母为零,则可能会出现异常。相应地引发异常,并通过为不同的异常打印不同的消息来捕获它 def divide(a, b): try: if b.isalpha(): raise ValueError('dividing by string not possible') c= a/b print('Result:', c) exc

通过异常处理查找两个数字的除法的程序。如果我的两个变量中的一个或两个都是字符串或分母为零,则可能会出现异常。相应地引发异常,并通过为不同的异常打印不同的消息来捕获它

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)

如果试图用字符串进行除法,则会出现
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:`

你的问题是什么?最后一行代码应该是
divide(3,'abc')
,而不是
divide(3,abc)