使用

  1. try:
  2. num = int(input("输入一个整数:"))
  3. result = 8 / num
  4. except ZeroDivisionError:
  5. print("除0错误")
  6. except Exception as e:
  7. print("未知错误 %s" % e)
  8. else:
  9. print("没有异常才会执行")
  10. finally:
  11. print("无论是否异常都会执行")
  12. print("---")

主动抛异常

  1. try:
  2. print("主动抛出异常")
  3. raise Exception("异常") # 关键字raise 抛异常
  4. except Exception as e:
  5. print(e)
  6. print("---")