异常处理 try/except/else/finally

1.try/finally结构

异常处理 try/except/else/finally_第1张图片

既要将异常向上传播,又要在异常发生时执行清理工作。

常见用途之一:确保程序能够可靠的关闭文件句柄

handle = open('filepath')  # 可能发生IOError
try:
    data = handle.read()  # 可能发生UnicodeDecodeError
finally:
    handel.close()  # 一定可以执行

2.try/except结构

异常处理 try/except/else/finally_第2张图片

3.try/except/else结构

清晰的描绘出哪些异常会由自己的代码来处理,哪些异常会传播到上一级。

异常处理 try/except/else/finally_第3张图片

4.抛出异常

Python 使用 raise 语句抛出一个指定的异常。

raise语法格式如下:

raise [Exception [, args [, traceback]]]

5.用户自定义异常

可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 Exception 类,可以直接继承,或者间接继承。

当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:

class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class InputError(Error):
    """Exception raised for errors in the input.

    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """

    def __init__(self, expression, message):
        self.expression = expression
        self.message = message

class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """

    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message

参考:https://www.cnblogs.com/yifanrensheng/p/12828734.html and https://www.runoob.com/python3/python3-errors-execptions.html

Notes:

1.无论 try 块是否发生异常,都可以利用 finally 块来清理异常;

2.else 块可以用来缩减 try 块中的代码量,并把没有发生异常时所要执行的语句与 try/except 代码块隔开;

3. 顺利运行 try 块后,若想使某些操作能在 finally 块的清理代码之前执行,则可将这些操作写到 else 块中。

 

你可能感兴趣的:(python学习,python)