异常-finally-自定义异常等

- 异常就是错误,会导致程序崩溃并停止运行

- python中能监控并捕获到异常,将异常部位的程序进行修理使得程序正常运行

- 异常语法 try: except<异常类型>:

- 捕获通用异常 except Exception as e:

- 捕获具体异常 except <具体异常类型> as e:

- 捕获多个异常 except(异常类型1,异常类型2,……) as e: 可以分开写,也可以()一次性写

def upper1(data):
    try:
        re = data.upper()
    except:
        return '程序出错了,需要输入字符串类型'
    return re

result = upper1('kiiii')
print(result)
print('kiji'.upper())
result = upper1(233) # AttributeError: 'int' object has no attribute 'upper'
print(result)

def upper2(data):
    try:
        re = data.upper()
    except Exception as e:
        return '程序出错了:{}'.format(e)
    return re

result = upper2(233)
print(result)
print('===========')

def test():
    try:
        print('22222')
        1/0   #  一旦出错,后续的代码就不再执行,直接进入异常处理模块
        print('是否触发')
    except ZeroDivisionError as e:
        print(e)

test()

# def test1():
#     try:
#         print('22222')
#         print(name) # NameError: name 'name' is not defined
#     except ZeroDivisionError as e: # 如果捕获的异常与触发的异常不对应时,程序报错
#         print(e)

def test1():
    try:
        print('22222')
        print(name) # NameError: name 'name' is not defined
    except (ZeroDivisionError,NameError) as e: # 如果捕获的异常与触发的异常不对应时,程序报错
        print(e)
        print(type(e))  # e 不是一个字符串,是个类,dir()可以查看他有哪些方法
        print(dir(e))
test1()

def ghh(data):
    if data <5:
        print('>5')
    elif data>10:
        print('>10')
    elif data >15:
        print('>15')
    else:
        print('else')

ghh(25)

常用异常类型举例:

class Test(object):
    pass

t = Test()
try:
    t.name
except AttributeError as e:
    print(e)

d = {'name':'mark'}
try:
    d['age']
except KeyError as e:
    print('键值错误:',e)

l = [1,2,3]
try:
    l[4]
except IndexError as e:
    print(e)

name = 'mark'
try:
    int(name)
except ValueError as e:
    print(e)

def test(a):
    return a

try:
    test()
except TypeError as e:
    print(e)

- 异常中的finally: 无论是否发生异常,一定会执行的代码块

- 在函数中,即便在try或者except 中进行了return,也依然会执行finally中的代码块

- try语法至少要伴随except或者finally其中一个,必须2选一

def test():
    try:
        1/0
    except ZeroDivisionError as e:
        print(e)
    finally:
        print('finally')

test()

def test1():
    try:
        2/0
    except ZeroDivisionError as e:
        print('1111111')
        return e
    finally:
        print('finally')

print('========')
re = test1()
print(re)

def test2():
    try:
        print('try-test')
        return 'try over'
    except ZeroDivisionError as e:
        return e
    finally:
        print('finally')

print('=====')
re2 = test2()
print(re2)

def test3():
    try:
        1/0
    except ZeroDivisionError as e:
        print('异常触发')
        return e
    finally:
        return 'finally'


print('=====')
re3 = test3() # 异常正常触发了,但是在有finally的时候,最终选择了finally的return
print(re3)

def test4():
    try:
        print('try999')
        return 'try-test4'
    except ZeroDivisionError as e:
        print('异常触发')
        return e
    finally:
        print('finally-print')
        return 'finally-4'

print('=====')
re4 = test4() # 在有finally的时候,最终选择了finally的return
print(re4)

def test5():
    try:
        print('try-5')
        1/0
        print('try-555')
    finally:
        # print('finally-5')
        return 'finally-5'

# test5() # 会报错,但finally正常打印,finally中添加return,不报错
print('=====')
re5 = test5() #忽略异常,直接进入finally
print(re5)

- 自定义抛出异常 raise 异常类型(message)

- 为什么之前的内置异常中不需要添加message,因为python解释器中自动帮我们添加了

- 自定义异常类型:继承基类-Exception,在构造函数中定义错误信息

# custom 代表自定义的意思
def test(a):
    if a == 10:
        raise ValueError('Num 不可以是10')
    else:
        print('a = ',a)

test(3)

def test1(a):
    try:
        test(a)
    except ValueError as e:
        print(e)

test1(10)

class NumberError(Exception):
    def __init__(self,message):
        self.message = message


class NameLimitError(Exception):
    def __init__(self,message):
        self.message = message

def test4(name):
    if name == 'mark':
        raise NameLimitError('mark用户不可以被填写')
    else:
        print('用户为:',name)

def test5(num):
    if num < 50:
        raise NumberError('填入数字不能低于50')
    else:
        print('填入的数字为:',num)

print('===========')
try:
    test5(40)
except NumberError as e:
    print(e)

try:
    test4('mark')
except NameLimitError as e:
    print(e)

- 断言:assert 用于判断一个表达式,在表达式条件为false的时候触发异常

- assert expression,message

 (参见stu-system-test3)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值