第六章 异常

第零章 学前准备
第一章 数据结构 – 基本数据类型
第一章 数据结构 – 字符串
第一章 数据结构 – 列表、元组和切片
第一章 数据结构 – 字典
第一章 数据结构 – 集合
第一章 – 数组、队列、枚举
第一章 数据结构 – 序列分类
第二章 控制流程
第三章 函数也是对象 – 函数定义以及参数
第三章 函数也是对象 – 高阶函数以及装饰器
第三章 函数也是对象 – lambda 表达式、可调用函数及内置函数
第四章 面向对象编程 – 自定义类、属性、方法和函数
第四章 面向对象编程–魔术方法1
第四章 面向对象编程 – 魔术方法2
第四章 面向对象编程 – 可迭代的对象、迭代器和生成器
第四章 面向对象编程 – 继承、接口
第四章 面向对象编程 – 对象引用
第四章 面向对象编程–案例
第五章 文件操作
第六章 异常


第六章 异常

6.1 内置异常

异常层次结构:

BaseException
 ├── BaseExceptionGroup
 ├── GeneratorExit
 ├── KeyboardInterrupt
 ├── SystemExit
 └── Exception
      ├── ArithmeticError
      │    ├── FloatingPointError
      │    ├── OverflowError
      │    └── ZeroDivisionError
      ├── AssertionError
      ├── AttributeError
      ├── BufferError
      ├── EOFError
      ├── ExceptionGroup [BaseExceptionGroup]
      ├── 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
      ├── StopAsyncIteration
      ├── StopIteration
      ├── SyntaxError
      │    └── IndentationError
      │         └── TabError
      ├── SystemError
      ├── TypeError
      ├── ValueError
      │    └── UnicodeError
      │         ├── UnicodeDecodeError
      │         ├── UnicodeEncodeError
      │         └── UnicodeTranslateError
      └── Warning
           ├── BytesWarning
           ├── DeprecationWarning
           ├── EncodingWarning
           ├── FutureWarning
           ├── ImportWarning
           ├── PendingDeprecationWarning
           ├── ResourceWarning
           ├── RuntimeWarning
           ├── SyntaxWarning
           ├── UnicodeWarning
           └── UserWarning

6.2 触发异常

6.2.1 raise

raise 语句支持强制触发指定的异常。raise后面接异常类或实例。

try:
    open("database.sqlite")
except OSError:
    raise RuntimeError("unable to handle error")

# 结果
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: unable to handle error

6.2.2 raise from

from 会为异常对象设置 __cause__ 属性表明异常的是由谁直接引起的。处理异常时发生了新的异常,在不使用 from 时更倾向于新异常与正在处理的异常没有关联。而 from 则是能指出新异常是因旧异常直接引起的。这样的异常之间的关联有助于后续对异常的分析和排查。from 语法会有个限制,就是第二个表达式必须是另一个异常类、实例或None。当为None时,通过设置 __suppress_context__ 属性指定来明确禁止异常关联。

def func():
    raise ConnectionError

try:
    func()
except ConnectionError as exc:
    raise RuntimeError('Failed to open database') from exc
# 结果
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in func
ConnectionError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database

raise...from None

try:
    open('database.sqlite')
except OSError:
    raise RuntimeError from None
# 结果
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError

6.3 自定义异常

程序可以通过创建新的异常类命名自己的异常。不论是以直接还是间接的方式,异常都应从 Exception 类派生。异常类可以被定义成能做其他类所能做的任何事,但通常应当保持简单,它往往只提供一些属性,允许相应的异常处理程序提取有关错误的信息。

class MyException(Exception):
    pass

class MyExceptionDetailed(Exception):
    def __init__(self, details):
        self.details=details

    def __str__(self):
        return f"{
      
      self.__class__.__name__}:{
      
      self.details}"

try:
    raise MyException
except MyException as e:
    raise MyExceptionDetailed(details="some details")
Traceback (most recent call last):
File "//10.163.68.113/nfc资料/01 测试工具/03-自动化相关/learn_nfc_autotest/test_python.py", line 12, in <module>
    raise MyException
__main__.MyException

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "//10.163.68.113/nfc资料/01 测试工具/03-自动化相关/learn_nfc_autotest/test_python.py", line 14, in <module>
    raise MyExceptionDetailed(details="some details")
__main__.MyExceptionDetailed: MyExceptionDetailed:some details
class MyException(Exception):
    pass


class MyExceptionDetailed(Exception):
    def __init__(self, details):
        self.details = details

    def __str__(self):
        return f"{
      
      self.__class__.__name__}:{
      
      self.details}"


try:
    raise MyException
except MyException as e:
    raise MyExceptionDetailed(details="some details") from e
Traceback (most recent call last):
File "//10.163.68.113/nfc资料/01 测试工具/03-自动化相关/learn_nfc_autotest/test_python.py", line 13, in <module>
    raise MyException
__main__.MyException

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "//10.163.68.113/nfc资料/01 测试工具/03-自动化相关/learn_nfc_autotest/test_python.py", line 15, in <module>
    raise MyExceptionDetailed(details="some details") from e
__main__.MyExceptionDetailed: MyExceptionDetailed:some details

猜你喜欢

转载自blog.csdn.net/qq_31654025/article/details/132781049