Python异常处理
2021/12/14 20:19:10
本文主要是介绍Python异常处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一.教程
#常规异常处理 def spam(divideBy): try: return 42 / divideBy except ZeroDivisionError: print('Error: Invalid argument.') try: print(5/0) except ZeroDivisionError: print("you can't divide by zero!") else: print("ok") try: #文件不存在 with open(filename) as lin_file: a = lin_file.read() except FileNotFoundError: print("file not found") raise Exception('This is the error message.') #返回错误 #保存反向追踪 import traceback try: #raise Exception('This is the error message.') print(abc) #一个不存在变量 except: errorFile = open('errorInfo.txt', 'w') errorFile.write(traceback.format_exc()) errorFile.close() print('The traceback info was written to errorInf') #异常 except Exception as other: #将异常赋值给变量 class UppercaseException(Exception): pass words = ['eeenie', 'meenie', 'miny', 'Mo'] for word in words: if word.isupper(): raise UppercaseException(word) for place in sys.path: print(place)
二.断言
market_2nd = {'ns': 'green', 'ew': 'red', 'xx': 'yellow'} mission_16th = {'ns': 'red', 'ew': 'green'} def switchLights(stoplight): for key in stoplight.keys(): if stoplight[key] == 'green': stoplight[key] = 'yellow' elif stoplight[key] == 'yellow': stoplight[key] = 'red' elif stoplight[key] == 'red': stoplight[key] = 'green' assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight) switchLights(market_2nd) switchLights(mission_16th) #ns会变为绿的,ew方向为成为黄色,导致没有红色的,车会一直开,会拥堵 #执行时-O则禁用断言,不过通常是注释断言
三.实例
def boxPrint(symbol, width, height): if len(symbol) != 1: raise Exception('Symbol must be a single character string.') if width <= 2: raise Exception('Width must be greater than 2.') if height <= 2: raise Exception('Height must be greater than 2.') print(symbol * width) #打印 for i in range(height - 2): print(symbol + (' ' * (width - 2)) + symbol) print(symbol * width) for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)): try: boxPrint(sym, w, h) except Exception as err: #返回自定义错误 print('An exception happened: ' + str(err))
这篇关于Python异常处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python