异常处理

  1. class NegativeException(Exception): # 自定义异常
  2. def __init__(self, x):
  3. self.x = x
  4. def __str__(self):
  5. return str(self.x) + " is negative."
  6. def divide(x, y):
  7. try:
  8. result = x / y
  9. if x < 0:
  10. raise NegativeException(x)
  11. except (ZeroDivisionError,NegativeException) as e:
  12. print("ZeroDivisionError:", e)
  13. except Exception as e:
  14. print("Exception is:", e)
  15. else: # 当try执行成功时,会执行else分支
  16. print("else... result is ", result)
  17. finally:
  18. print("finally....")
  19. divide(-1, 2)
  20. # ZeroDivisionError: -1 is negative.
  21. # finally....
  22. divide(2, 0)
  23. # ZeroDivisionError: division by zero
  24. # finally....
  25. divide("2", "1")
  26. # Exception is: unsupported operand type(s) for /: 'str' and 'str'
  27. # finally....

链接:python异常处理