Chapter 9 exceptions and errors

Brief introduction

	异常指程序运行过程中出现的非正常现象,例如用户输入错误、除数为零、需 要处理的文件不存在、
数组下标越界等。 所谓异常处理,就是指程序在出现问题时依然可以正确的执行剩余的程序,而 不会
因为异常而终止程序执行。
	python 中,引进了很多用来描述和处理异常的类,称为异常类。异常类定义中 包含了该类异常的信
息和对异常进行处理的方法。

The following shows a more complete inheritance hierarchy in python built-in exception classes:
Here Insert Picture Description
python, everything is an object, but also by way of an exception object to deal with. Process:

1. throw an exception:

	在执行一个方法时,如果发生异常,则这个方法生成代表该 异常的一个对象,停止当前执行路径,
并把异常对象提交给解释器。

2. catch exceptions:

	解释器得到该异常后,寻找相应的代码来处理该异常。

A, try ... except a structure

try ... except the most common exception-handling structure. Structured as follows:

			try: 
				被监控的可能引发异常的语句块 
			except BaseException [as e]: 
				异常处理语句块 
	try 块包含着可能引发异常的代码,except 块则用来捕捉和处理发生的异常。执行的时 候,如果try块
中没有引发异常,则跳过 ecept 块继续执行后续代码;
	执行的时候,如果 try块中发生了异常,则跳过 try 块中的后续代码,跳到相应的except块中处理异常;			
异常处理完后,继续执行后续代码。

Two, try ... except construct more

	上面的结构可以捕获所有的异常,工作中也很常见。但是,从经典理论考虑,一般建议尽量捕获
可能出现的多个异常(按照先子类后父类的顺序),并且针对性的写出异常处理代 码。为了避免遗
漏可能出现的异常,可以在最后增加 BaseException。结构如下:
			try: 
				被监控的、可能引发异常的语句块 
			except Exception1: 
				处理 Exception1 的语句块 
			except Exception2: 
				处理 Exception2 的语句块 
			... 
			...
			...
			except BaseException: 
				处理可能遗漏的异常的语句块

Three, try ... except ... else structure

	try...except...else结构增加了“else 块”。如果try块中没有抛出异常,则执行 else 块。如果try块中
抛出异常,则执行except块,不执行else块。

Four, try ... except ... finally structure

	try...except...finally 结构中,finally块无论是否发生异常都会被执行;通常用来释放 try 块中申请
的资源。

Five, return statements and exception handling issues

	由于return有两种作用:结束方法运行、返回值。我们一般不把return放到异常处理结构中,而是
放到方法最后。

Sample code:

def test01():
    print("step1")
    try:
        x = 3/0
        # return "a"
    except:
        print("step2")
        print("异常:0 不能做除数")
        # return "b"
    finally:
        print("step3")
        # return "c"
    print("step4")
    # 一般不要将return语句放到try、except、else、 finally块中,
    # 会发生一些意想不到的错误。建议放到方法最后。
    return "d"


print(test01())
=====================运行结果=============================
step1
step2
异常:0 不能做除数
step3
step4
e
=====================运行结果=============================

Six common exceptions summary

Here Insert Picture Description
Here Insert Picture Description

Seven, with context management

	finally块由于是否发生异常都会执行,通常我们放释放资源的代码。其实,我们可以通过with上下文
管理,更方便的实现释放资源的操作。

Grammatical structures with context management as follows:

	with context_expr [ as var]: 
		语句块
		
	with 上下文管理可以自动管理资源,在with代码块执行完毕后自动还原进入该代码之前的现场
或上下文。不论何种原因跳出with块,不论是否有异常,总能保证资源正常释放。极大的简化了工
作,在文件操作、网络通信相关的场合非常常用。

Eight, trackback module

Traceback abnormality information using the print module, the sample code:

import traceback

file_path = "E:\PythonProject\File_Test\学习文件\\file01.txt"
try:
    a = 1 / 0
except:
    traceback.print_exc()  # 打印异常信息
    with open(r"{0}".format(file_path), "a") as f:
        traceback.print_exc(file=f)   # 使用 traceback 将异常信息写入日志文件
        print('写入信息!!!')
=====================运行结果=============================
Traceback (most recent call last):
  File "E:/PythonProject/CSDNPythonLearn/exception/exception_test02.py", line 5, in <module>
    a = 1 / 0
ZeroDivisionError: division by zero
=====================运行结果=============================

Nine, custom exception class

	程序开发中,有时候我们也需要自己定义异常类。自定义异常类一般都是运行时异常,通常
继承Exception或其子类即可。命名一般以Error、Exception为后缀

Sample code:

class ScoreError(Exception):

    def __init__(self, error_info):
        Exception.__init__(self)
        self.error_info = error_info

    def __str__(self):
        return str(self.error_info) + '录入分数错误,应在0-101之间!!!'


if __name__ == "__main__":
    score = int(input("请输入一个分数:"))
    if score < 0 or score > 100:
        raise ScoreError(score)
    else:
        print("分数输入正确,请确认:{0}".format(score))
=====================运行结果=============================
请输入一个分数:777
Traceback (most recent call last):
  File "E:/PythonProject/CSDNPythonLearn/exception/exception_test03.py", line 14, in <module>
    raise ScoreError(score)
__main__.ScoreError: 777录入分数错误,应在0-101之间!!!
=====================运行结果=============================

Learning From: Beijing Shangxue Tang Gao Qi teacher Python 400 set

Published 20 original articles · won praise 6 · views 20000 +

Guess you like

Origin blog.csdn.net/XuanAlex/article/details/104677891