Python3之異常處理


寫自動化腳本時經常會用到異常處理,下面將python中的異常處理做一整理:

 

 

注意:以下所有事列中的111.txt文件不存在,所以會引起異常

用法一:try...except...else..類型

1.沒有異常時運行:

a = 3
try:
    print(a)
except BaseException as msg:   #用msg變量來接受信息,並將其打印。其中BaseException為所有異常的基類,所有異常都繼承與它
    print(msg)
else:
    print("沒有異常時執行")

運行結果:

3
沒有異常時執行

2.有異常時運行:

a = 3
b = 4
try:
    print(a)
    open("111.txt",'r')       #使用open以只讀的方式打開不存在的文件111.txt
    print(b)
except BaseException as msg:  #用msg變量來接受信息並將其打印
    print(msg)
else:
    print("沒有異常時執行")

運行結果:

3
[Errno 2] No such file or directory: '111.txt'     ##該條錯誤信息是msg接收到的信息

上面代碼中的print(b)並沒有被執行,因為再該行代碼的上一步出現異常

 

用法二:try...except...finally...類型

1.沒有異常時運行:

a = 3
try:
    print(a)
except BaseException as msg:
    print(msg)
finally:
    print("不管有沒有異常都會被執行")

運行結果:

3
不管有沒有異常都會被執行

2.有異常時運行:

a = 3
try:
    print(a)
    open('111.txt','r')
except BaseException as msg:   
    print(msg)
finally:
    print("不管有沒有異常都會被執行")

運行結果:

3
[Errno 2] No such file or directory: '111.txt'
不管有沒有異常都會被執行

 

 

用法三:拋出異常(raise)

a = 3
try:
    print(a)
    open('111.txt','r')
except:
    raise Exception('111.txt no exsit')  #raise用於異常拋出

運行結果:

3
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '111.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>           #拋出異常
Exception: 111.txt no exsit

 

自定義異常

class TimeError(RuntimeError):       #定義一個異常類,該類應該是典型的繼承自Exception類,通過直接或間接的方式
    def __init__(self,arg):
        self.arg = arg


try:
    raise TimeError("Network timeout")   #自定義異常提示
except TimeError as e:
    print(e.arg)

運行結果:

Network timeout

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM