本章知识点:
1、try...except语句;2、raise语句;3、assert语句;4、自定义异常;5、程序调试;
内容:
9.1 异常的处理
9.1.1 Python中的异常
1 | StopItertion | 当迭代器中没有数据项时触发,由内置函数next()和迭代器的__next__()方法触发。 |
2 | ArithmeticError | 算法异常的基类,包括OverflowError(溢出异常)、ZeroDivisionError(零除异常)和FloatingPointError(失败的浮点数操作)。 |
3 | AssertionError | assert语句失败时触发。 |
4 | AttributeError | 属性引用和属性赋值异常。 |
9.1.2 try...except的使用
1 ## finally错误的用法2 try:3 f = open("hello.txt", "r")4 print ("读文件")5 except FileNotFoundError:6 print ("文件不存在")7 finally:8 f.close()9 # 输出:读文件
1 try:2 open("hello.txt", "r")3 print ("读文件")4 except FileNotFoundError:5 print ("文件不存在")6 except:7 print ("程序异常")8 # 输出:文件不存在
1 try:2 result = 10/03 except FileNotFoundError:4 print ("0不能被整除")5 else:6 print (result)7 # 输出:文件不存在8 # 输出:ZeroDivisionError: division by zero
1 try: 2 s = "hello" 3 try: 4 print (s[0] + s[1]) 5 print (s[0] - s[1]) 6 except TypeError: 7 print ("字符串不支持减法运算") 8 except: 9 print ("异常")10 # 输出:he11 # 字符串不支持减法运算
9.1.3 try...finally的使用
1 ## finally错误的用法2 try:3 f = open("hello.txt", "r")4 print ("读文件")5 except FileNotFoundError:6 print ("文件不存在")7 finally:8 f.close()9 # 输出:读文件
1 try: 2 f = open("hello.txt", "r") 3 try: 4 print (f.read(5)) 5 except: 6 print ("读取文件错误") 7 finally: 8 print ("释放资源") 9 f.close()10 except FileNotFoundFrrpr:11 print ("文件不存在")12 # 输出:hello13 # 释放资源
9.1.4 使用raise抛出异常
1 try:2 s = None3 if s is None:4 print ("s是空对象")5 raise NameError6 print (len(s))7 except TypeError:8 print ("空对象没有长度")
9.1.5 自定义异常
1 from __future__ import division 2 class DivisionException(Exception): 3 def __init__(self, x, y): 4 Exception.__init__(self, x, y) 5 self.x = x 6 self.y = y 7 if __name__ == "__main__": 8 try: 9 x = 310 y = 211 if x % y > 0:12 print (x / y)13 raise DivisionException(x, y)14 except DivisionException,div:15 print ("DivisionException:x / y = %.2f" % (div.x / div.y))
9.1.6 assert语句的使用
1 t = ("hello",)2 assert len(t) >= 13 t = ("hello")4 assert len(t) == 1
1 month = 132 assert 1 <= month <= 12, "month errors"
9.1.7 异常信息
1 import sys2 try:3 x = 10 / 04 except Exception as ex:5 print (ex)6 print (sys.exc_info())7 # 输出:division by zero8 # (, ZeroDivisionError('division by zero',), )
9.2 使用自带IDLE调试程序
1 def fun():2 a = 103 b = 04 return a / b5 def format():6 print ("a / b =" + str(fun()))