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异常处理

上一篇:windws激活


下一篇:photoshop利用图案及图层样式制作绿色格子布纹水晶字