异常处理
class NegativeException(Exception): # 自定义异常
def __init__(self, x):
self.x = x
def __str__(self):
return str(self.x) + " is negative."
def divide(x, y):
try:
result = x / y
if x < 0:
raise NegativeException(x)
except (ZeroDivisionError,NegativeException) as e:
print("ZeroDivisionError:", e)
except Exception as e:
print("Exception is:", e)
else: # 当try执行成功时,会执行else分支
print("else... result is ", result)
finally:
print("finally....")
divide(-1, 2)
# ZeroDivisionError: -1 is negative.
# finally....
divide(2, 0)
# ZeroDivisionError: division by zero
# finally....
divide("2", "1")
# Exception is: unsupported operand type(s) for /: 'str' and 'str'
# finally....
链接:python异常处理