-
我们在编写代码时,可以自定义异常,这样方便查错
-
直接看例子就可以
- 这个例子是写一个函数来打印指定文件的第一行
- 使用错误代码和错误说明描述我们自己定义的异常
# 测试准备 dream:tmp dream$ cd /tmp/testForException/ # 测试的目录 dream:testForException dream$ touch file1.txt # file1.txt为空 dream:testForException dream$ echo -e 'aaaa\nbbbb\ncc' > file2.txt # file2.txt写入信息 dream:testForException dream$ ls file1.txt file2.txt dream:testForException dream$ cat file2.txt aaaa bbbb cc # 测试代码 In [1]: import os In [3]: os.chdir('/tmp/testForException/') In [4]: os.getcwd() Out[4]: '/private/tmp/testForException' In [5]: os.system('ls') file1.txt file2.txt Out[5]: 0 In [9]: class DirNotExist(Exception): # 自定义的异常都是基础Exception类的 ...: def __init__(self): ...: self.code = 100 ...: self.description = '该文件所在目录不存在' ...: In [10]: class FileNotExist(Exception): ...: def __init__(self): ...: self.code = 101 ...: self.description = '该文件不存在' ...: In [11]: class FileIsEmpty(Exception): ...: def __init__(self): ...: self.code = 101 ...: self.description = '该文件为空' ...: In [24]: def printOneLine(file_path): ...: ''' ...: 该函数作用为打印指定文件的第一行,错误类型如下: ...: code=100-->文件所在目录不存在 ...: code=101-->文件不存在 ...: code=102-->文件为空 ...: ''' ...: try: ...: if not os.path.exists(os.path.dirname(file_path)): ...: raise DirNotExist() ...: if not os.path.exists(os.path.basename(file_path)): ...: raise FileNotExist() ...: if os.path.getsize(file_path) == 0: ...: raise FileIsEmpty() ...: with open(file_path, mode='r', encoding='utf-8') as f: ...: print(f.readline()) ...: ...: except DirNotExist as e: ...: print(e.code, ': ', e.description) ...: except FileNotExist as e: ...: print(e.code, ': ', e.description) ...: except FileIsEmpty as e: ...: print(e.code, ': ', e.description) ...: except Exception as e: ...: print(e) ...: # 测试结果 In [25]: printOneLine('/tmp/testForException/file1.txt') 101 : 该文件为空 In [26]: printOneLine('/tmp/testForException/file2.txt') aaaa In [27]: printOneLine('/tmp/testForException/file3.txt') 101 : 该文件不存在 In [28]: printOneLine('/tmp/xxx/file3.txt') 100 : 该文件所在目录不存在
- 当执行
raise DirNotExist()
时,先实例化该对象,然后再抛出异常对象 - 被抛出的异常对象会被下面的
except ·· as e
按顺序查看是否能捕获
python-自定义异常
最新推荐文章于 2024-07-22 14:28:34 发布