天天看點

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異常處理

本文版權歸作者所有,歡迎轉載,請務必添加原文連結。