ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python异常处理

2021-12-14 18:03:10  阅读:134  来源: 互联网

标签:Exception Python except 处理 key print 异常 stoplight red


一.教程

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

标签:Exception,Python,except,处理,key,print,异常,stoplight,red
来源: https://www.cnblogs.com/rxysg/p/15689202.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有