异常
- raise 语句
在第一个实例(raise Exception)中,引发的是通用异常,没有指出出现什么错误。在第二个实例中,添加了错误消息hyperdrive overload.

一些内置的异常类
类名 描述
Exception 几乎所有的异常类都是从它派生而来的
AttributeError 引用属性或给它赋值失败时引发
OSError 操作系统不能执行指定的任务(如打开文件)时引发,有多个子类
IndexError 使用序列中不存在的索引时引发,为LookupError的子类
KeyError 使用映射中不存在的键时引发,为LookupError的子类
NameError 找不到名称(变量)时引发
SyntaxError 代码不正确时引发
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.






浙公网安备 33010602011771号