• python基础入门之十七 —— 异常


    一、定义

    当检测到一个错误时,解释器就无法继续进行了,反而出现一些错误的提示,这就是所谓的异常。

    语法:

    try:
        可能发生的错误代码
    except:
        如果出现异常执行的代码  
    # 捕获指定异常: 这里是‘NameError’
    try:
        print(a)
    except NameError as result:
        print(result)   # name 'a' is not defined
    
    # 捕获所有异常 :Exception
    try:
        print(b)
    except Exception as result:
        print(result)   # name 'c' is not defined
    
    # 如果尝试执行的代码的异常类型和要捕获的异常类型不一致,则无法捕获异常。
    try:
        print(b)
    except IOError as result:
        print(result)   # 报错

    二、else/finally

    try:
        print(1) # 1
    except Exception as result :
        print(result)
    else:
        print('没有异常时执行的代码')  # 没有异常时执行的代码
    finally:
        print('无论是否异常都要执行的代码')  # 无论是否异常都要执行的代码
    
    try:
        print(i)
    except Exception as result :
        print(result)  # name 'i' is not defined
    else:
        print('没有异常时执行的代码')
    finally:
        print('无论是否异常都要执行的代码')  # 无论是否异常都要执行的代码

    三、自定义异常

    raise 抛出异常

    class ShortInputError(Exception):
        def __init__(self,length,min_len):
            self.length = length
            self.min_len = min_len
    
        def __str__(self):
            return f'你输入的长度是{self.length},不能少于{self.min_len}'
    
    
    try:
        con = input('input:')
        if len(con)<3:
            raise ShortInputError(len(con),3)
    except Exception as res:
        print(res)
  • 相关阅读:
    [论文复现笔记]Im2Struct
    深度学习踩坑
    Matlab问题汇总
    Linux网络服务
    探索Blender
    [每日挖坑]20200728
    Ubuntu重启之后显卡挂了
    3D视觉知识点
    [每日挖坑]20200727
    遥感影像相关知识
  • 原文地址:https://www.cnblogs.com/LynHome/p/12627700.html
Copyright © 2020-2023  润新知