程序查找两个数字的除法,并进行异常处理。如果两个变量中的一个或两个都是字符串或分母为零,则可能出现异常。相应地引发异常,并针对不同的异常打印不同的消息来捕获异常。在
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
块捕获不同类型的异常,并以不同的方式处理它们。在示例:
相关问题 更多 >
编程相关推荐