python-自定義異常

  • 我們在編寫代碼時,可以自定義異常,這樣方便查錯

  • 直接看例子就可以

    • 這個例子是寫一個函數來打印指定文件的第一行
    • 使用錯誤代碼和錯誤說明描述我們自己定義的異常
    # 測試準備
    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按順序查看是否能捕獲
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章