Python 异常概览

异常简介(Built-in Exceptions)

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

python 中,所有的异常都派生自 BaseException 类,它是所有异常的 基类。内置异常类可以被子类化以定义新的异常,如果我们需要自定义一个异常,我们应该从 [Exception] 类或它的某个子类而不是从 [BaseException] 来派生新的异常

In Python, all exceptions must be instances of a class that derives from [BaseException]. In a [try] statement with an [except] clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.

(在 Python 中,所有异常必须为一个派生自 [BaseException]的类的实例。 在带有提及一个特定类的 [except]子句的 [try]语句中,该子句也会处理任何派生自该类的异常类(但不处理 所派生出的异常类)。 通过子类化创建的两个不相关异常类永远是不等效的,既使它们具有相同的名称)

——Built-in Exceptions — Python 3.9.5 documentation

该文档主要参考以下资料:

Built-in Exceptions — Python 3.9.5 documentation

warnings — Warning control — Python 3.9.5 documentation

异常的层次结构

python 中的异常分为 4 种类型,它们都继承自 BaseException

异常类型异常介绍
SystemExit程序意外退出异常
KeyboardInterrupt用户按下中断键键异常,通常为 Control-C 或 Delete
GeneratorExit生成器被关闭引发的异常
Exception所有内置的非系统退出类异常都派生自此类, 所有用户自定义异常也应当派生自此类
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError 
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

异常的捕获

  • 捕获异常说明

    用户代码可以引发内置异常。 这可被用于测试异常处理程序或报告错误条件,“就像” 在解释器引发了相同异常的情况时一样;但是请注意,没有任何机制能防止用户代码引发不适当的错误,所有的异常捕获都是在猜测某段代码可能会发生异常

  • 捕获异常的语法

    try:
        可能发生错误的代码
    except:
        如果出现异常执行的代码
    
  • 捕获异常的使用

    ① 捕获所有继承自 Exception 的异常

    try:
        a = 1 / 0
    except Exception:
        print('除法或取余运算的第二个参数不能为零!')
    

    ③ 捕获指定的异常

    try:
        print(1/0)
    
    except ZeroDivisionError:
        print('除法或取余运算的第二个参数不能为零!')
    

    ③ 捕获多个指定的异常

    try:
        print(1/0)
    
    except (NameError, ZeroDivisionError):
        print('除法或取余运算的第二个参数不能为零!')
    

异常的流程控制

  • else 没有异常发生时的操作
try:
    print(1)
except Exception as result:
    print(result)
else:
    print('没有发生异常!')
  • finally 异常发生后也会执行的操作

    finally 表示的是无论是否异常都要执行的代码,例如关闭文件

    try:
        f = open('test.txt', 'r')
    except Exception as result:
        f = open('test.txt', 'w')
    else:
        print('没有异常,真开心')
    finally:
        f.close()
    

自定义并抛出一个异常

  • 引发一个自定义或内置异常

    # 引发一个内置异常
    raise FileExistsError
    
    # 引发一个内置异常
    ex = Exception('这是一个内置异常!')
    raise ex
    
  • 自定义一个派生自 Exception 的异常类

    class ShortInputError(Exception):
        """
        自定义异常类,继承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}个字符'
    
    
    if __name__ == '__main__':
    
        try:
            password = input('请输入你的密码!')
            if len(password) < 6:
                raise ShortInputError(len(password), 6)
        except ShortInputError as result:
            print(result)
        else:
            print('密码输入符合规范!')
    
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值