异常

  • 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.

相关文章
相关标签/搜索