前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python异常处理(上)

Python异常处理(上)

原创
作者头像
陈不成i
修改2021-06-18 18:08:41
2800
修改2021-06-18 18:08:41
举报
文章被收录于专栏:ops技术分享ops技术分享

一.教程

  1. #常规异常处理
  2. def spam(divideBy):
  3. try:
  4. return 42 / divideBy
  5. except ZeroDivisionError:
  6. print('Error: Invalid argument.')
  7. try:
  8. print(5/0)
  9. except ZeroDivisionError:
  10. print("you can't divide by zero!")
  11. else:
  12. print("ok")
  13. try: #文件不存在
  14. with open(filename) as lin_file:
  15.         a = lin_file.read()
  16. except FileNotFoundError:
  17. print("file not found")
  18. raise Exception('This is the error message.') #返回错误
  19. #保存反向追踪
  20. import traceback
  21. try:
  22. #raise Exception('This is the error message.')
  23. print(abc) #一个不存在变量
  24. except:
  25.     errorFile = open('errorInfo.txt', 'w')
  26.     errorFile.write(traceback.format_exc())
  27.     errorFile.close()
  28. print('The traceback info was written to errorInf')
  29. #异常
  30. except Exception as other: #将异常赋值给变量
  31. class UppercaseException(Exception):
  32. pass
  33. words = ['eeenie', 'meenie', 'miny', 'Mo']
  34. for word in words:
  35. if word.isupper():
  36. raise UppercaseException(word)
  37. for place in sys.path:
  38. print(place)

二.断言

  1. market_2nd = {'ns': 'green', 'ew': 'red', 'xx': 'yellow'}
  2. mission_16th = {'ns': 'red', 'ew': 'green'}
  3. def switchLights(stoplight):
  4. for key in stoplight.keys():
  5. if stoplight[key] == 'green':
  6.             stoplight[key] = 'yellow'
  7. elif stoplight[key] == 'yellow':
  8.             stoplight[key] = 'red'
  9. elif stoplight[key] == 'red':
  10.             stoplight[key] = 'green'
  11. assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight)
  12. switchLights(market_2nd)
  13. switchLights(mission_16th) #ns会变为绿的,ew方向为成为黄色,导致没有红色的,车会一直开,会拥堵
  14. #执行时-O则禁用断言,不过通常是注释断言

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一.教程
  • 二.断言
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档