異常

  • raise 語句

        在第一個實例(raise Exception)中,引起的是通用異常,沒有指出出現什麼錯誤。在第二個實例中,添加了錯誤消息hyperdrive overload.app

        

         

          一些內置的異常類函數

               類名                                                                                         描述spa

Exception                                                                                 幾乎全部的異常類都是從它派生而來的操作系統

AttributeError                                                                           引用屬性或給它賦值失敗時引起3d

OSError                                                                                   操做系統不能執行指定的任務(如打開文件)時引起,有多個子類code

IndexError                                                                                使用序列中不存在的索引時引起,爲LookupError的子類對象

KeyError                                                                                  使用映射中不存在的鍵時引起,爲LookupError的子類blog

NameError                                                                               找不到名稱(變量)時引起索引

SyntaxError                                                                              代碼不正確時引起ip

TypeError                                                                                 將內置操做或函數用戶類型不正確的對象時引起

ValueError                                                                                將內置操做或者用於這樣的對象時引起:其類型正確但包含的值不適合

ZeroDivisionError                                                                      在除法或求模運算的第二個參數爲零時引起

    

            自定義的異常類

               自定義異常代碼

               class SomeCustomException(Exception): pass

               

               捕獲異常     

這個程序運行正常,直到用戶輸入的第二個數爲零.
1
x = int(input('Enter the firsh number: ')) 2 y = int(input('Enter the second number: ')) 3 print(x / y)
執行結果
    
爲捕獲這種異常並對錯誤進行處理,可想像下面這樣重寫這個程序:
1
try: 2 x = int(input('Enter the firsh number: ')) 3 y = int(input('Enter the second number: ')) 4 print(x / y) 5 except ZeroDivisionError: 6 print("The second number cant't be zero!")
執行結果

 

          不用提供參數

 1 class MuffledCalculator:
 2     muffled = False
 3     def calc(self, expr):
 4         try:
 5             return eval(expr)
 6         except ZeroDivisionError:
 7             if self.muffled:
 8                 print('Division by zero is illegal')
 9             else:
10                 raise
11 calculator = MuffledCalculator()
12 a=calculator.calc('10 / 2')
13 print(a)
執行結果
 發生除零行爲時,關閉抑制功能,捕獲了異常ZeroDivisionError,但繼續向上傳播它
1
class MuffledCalculator: 2 muffled = False 3 def calc(self, expr): 4 try: 5 return eval(expr) 6 except ZeroDivisionError: 7 if self.muffled: 8 print('Division by zero is illegal') 9 else: 10 raise 11 calculator = MuffledCalculator() 12 b=calculator.calc('10 / 0') 13 print(b)
執行結果
 發生除零行爲時,若是啓用了「抑制」功能,方法calc將(隱式地)返回None.
1
class MuffledCalculator: 2 muffled = False 3 def calc(self, expr): 4 try: 5 return eval(expr) 6 except ZeroDivisionError: 7 if self.muffled: 8 print('Division by zero is illegal') 9 else: 10 raise 11 calculator = MuffledCalculator() 12 calculator.muffled = True 13 b=calculator.calc('10 / 0') 14 print(b)
執行結果
     

  

           一舉兩得   

若是要使用一個except子句捕獲多種異常,可在一個元組中指定這些異常,以下所示:
1
try: 2 x = int(input('Enter the firsh number: ')) 3 y = int(input('Enter the second number: ')) 4 print(x / y) 5 except (ZeroDivisionError, TypeError, NameError): 6 print('Your numbers were bogus ...')
執行結果

 

          捕獲對象

要在except子句中訪問異常對象自己,可以使用兩個而不是一個參數.
1
try: 2 x = int(input('Enter the firsh number: ')) 3 y = int(input('Enter the second number: ')) 4 print(x / y) 5 except (ZeroDivisionError, TypeError) as e: 6 print(e)
執行結果
   

 

           一網打盡           

  即便程序處理了好幾種異常,仍是可能有一些漏網之魚,有些異常未被try/except語句捕獲,在這些狀況下,與其使用並不是要捕獲這些異常的try/except
語句將他們隱藏起來,還不如讓程序立刻崩潰.
1
try: 2 x = int(input('Enter the firsh number: ')) 3 y = int(input('Enter the second number: ')) 4 print(x / y) 5 except: 6 print('something wrong happened ...')
執行結果
   

 

          萬事大吉時

在這裏,僅當沒有引起異常時,纔會跳出循環.
1
while True: 2 try: 3 x = int(input('Enter the firsh number: ')) 4 y = int(input('Enter the second number: ')) 5 print(x / y) 6 except: 7 print('Invalid input.Please try again.') 8 else: 9 break
執行結果
 使用空的except子句來捕獲全部屬於類exception(或其子類)的異常.
1
while True: 2 try: 3 x = int(input('Enter the firsh number: ')) 4 y = int(input('Enter the second number: ')) 5 value = x / y 6 print('x / y is ', value) 7 except Exception as e: 8 print('Invalid input:' , e) 9 print('Please try again') 10 else: 11 break
執行結果

 

         異常之禪

假設有一個字典,你要在指定的鍵存在時打印與之關聯的值,不然什麼都不作.
1
def describe_person(**person): 2 print('Description of', person['name']) 3 print('Age:', person['age']) 4 if 'occupation' in person: 5 print('occupation:', person['occupation']) 6 describe_person(name='xiaoming', age=12 , occupation='camper')
執行結果
   
 下面是另外一種解決方法:
1
def describe_person(**person): 2 print('Description of', person['name']) 3 print('Age:', person['age']) 4 try: 5 print('occupation:', person['occupation']) 6 except KeyError: 7 pass 8 print('no occupation') 9 10 describe_person(name='xiaoming', age=12 )
執行結果
    

 

            不那麼異常的狀況

            若是你只是想發出警告,指出狀況偏離了正軌,可以使用模塊warnings中的函數warn,警告只顯示一次,若是再次運行最後一行代碼,什麼事情都不會發生

           

  若是其餘代碼在使用你的模塊,可以使用模塊warnings中的函數filterwarnings來抑制你發出的警告(或特定類型的警告),並指定要採起的措施,如
"error"或"igonre".
>>> from warnings import filterwarnings >>> filterwarnings("ignore") >>> warn("Anyone out there?") >>> filterwarnings("error") >>> warn("Something is very wrong!") Traceback (most recent call last): File "<stdin>", line 1, in <module> UserWarning: Something is very wrong!

發出警告時,可指定將引起的異常(即警告類別),但必須是warnings的子類.若是將警告類別轉化爲錯誤,將使用你指定的異常

  >>> filterwarnings("error")  >>> warn("This function is really old ...", DeprecationWarning)  Traceback (most recent call last):  File "<stdin>", line 1, in <module>  DeprecationWarning: This function is really old ...  >>> filterwarnings("ignore", category=DeprecationWarning)  >>> warn("Another deprecation warning.", DeprecationWarning)  >>> warn("something else.")  Traceback (most recent call last):  File "<stdin>", line 1, in <module>  UserWarning: something else.

相關文章
相關標籤/搜索