8.1 什么是异常
每个异常都是一些类的实例
8.2 按自己的方式出错
8.2 raise语句
>>> raise Exception Traceback (most recent call last): File "", line 1, in Exception
>>> raise Exception('hyperdrive overload') Traceback (most recent call last): File "", line 1, in Exception: hyperdrive overload
查看内建异常
>>> import exceptions >>> dir(exceptions) ['ArithmeticError', 'AssertionError',...]
8.2.2 自定义异常类
class SomeCustomException(Exception):pass
8.3 捕捉异常
try: x=input('Enter the first number:') y=input('Enter the second number:') print x/y except ZeroDivisionError: print "The second number can't be zero!" ... Enter the first number:10 Enter the second number:0 The second number can't be zero!
看,没参数
>>> class MuffedCalculator: ... muffled=False ... def calc(self,expr): ... try: ... return eval(expr) ... except ZeroDivisionError: ... if self.muffled: ... print 'Division by zero is illegal' ... else: ... raise ... >>> >>> calculator=MuffedCalculator() >>> calculator.calc('10/2') 5 >>> calculator.calc('10/0') Traceback (most recent call last): File "", line 1, in File " ", line 5, in calc File " ", line 1, in ZeroDivisionError: integer division or modulo by zero >>> calculator.muffled=True >>> calculator.calc('10/0') Division by zero is illegal
8.4 不止一个except子句
>>> try: ... x=input('Enter the first number:') ... y=input('Enter the second number:') ... print x/y ... except ZeroDivisionError: ... print "The second number can't be zero!" ... except TypeError: ... print "That wasn't a number,was it?" ... Enter the first number:10 Enter the second number:"Hello world!" That wasn't a number,was it?
8.5 用一个会捕捉两个异常
>>> try: ... x=input('Enter the first number:') ... y=input('Enter the second number:') ... print x/y ... except (ZeroDivisionError,TypeError,NameError): ... print "Your numbers were bogus....." ... Enter the first number:10 Enter the second number:0 Your numbers were bogus.....
8.6 捕捉对象
#访问异常对象本身
>>> try: ... x=input('Enter the first number:') ... y=input('Enter the second number:') ... print x/y ... except (ZeroDivisionError,TypeError,NameError),e: ... print "Your numbers were bogus....." ... print e ... Enter the first number:10 Enter the second number:0 Your numbers were bogus..... integer division or modulo by zero
8.7 真正的全捕捉
缺点:会隐藏所有程序员未想到并且未做好准备的错误
>>> try: ... x=input('Enter the first number:') ... y=input('Enter the second number:') ... print x/y ... except: ... print "Someting wrong happened...." ... Enter the first number: Someting wrong happened....
推荐用下面的方式:
>>> try: ... x=input('Enter the first number:') ... y=input('Enter the second number:') ... print x/y ... except Exception,e: ... print "Someting wrong happened...." ... print e ... Enter the first number:10 Enter the second number:0 Someting wrong happened.... integer division or modulo by zero
8.8 万事大吉
else:没有异常的时候会执行
>>> try: ... print 'A simple task' ... except: ... print 'What?something went wrong?' ... else: ... print 'Ah....It went as planned..' ... A simple task Ah....It went as planned..
while True: try: x=input('Enter the first number:') y=input('Enter the second number:') value=x/y print 'x/y is',value except: print 'Invalid input,Please try again.' else: break
while True: try: x=input('Enter the first number:') y=input('Enter the second number:') value=x/y print 'x/y is',value except Exception,e: print 'Invalid input',e print 'Please try again' else: break
8.9 最后....
finally:如果需要确保某些代码不管是否有异常都执行
>>> x=None >>> try: ... x=1/0 ... finally: ... print 'Cleaning up....' ... del x ... Cleaning up.... Traceback (most recent call last): File "", line 2, in ZeroDivisionError: integer division or modulo by zero
>>> try: ... 1/0 ... except NameError: ... print 'Unknown variable' ... else: ... print 'That went well!' ... finally: ... print 'Cleaning up.' ... Cleaning up. Traceback (most recent call last): File "", line 2, in ZeroDivisionError: integer division or modulo by zero
8.10 异常和函数
>>> def faulty(): ... raise Exception('Someting is wrong') ... >>> def ignore_exception(): ... faulty() ... >>> def handle_exception(): ... try: ... faulty() ... except: ... print 'Exception handled' ...
>>> ignore_exception() Traceback (most recent call last): File "", line 1, in File " ", line 2, in ignore_exception File " ", line 2, in faulty Exception: Someting is wrong >>> handle_exception() Exception handled
8.11 异常之禅
使用try/except 语句比if/else语句更自然一些
>>> def describePersion(person): ... print 'Description of',person['name'] ... print 'age:',person['age'] ... if 'occupation' in person: ... print 'Occupation:',person['occupation'] ...
>>> person={'name':'jack','age':10,'occupation':'camper'} >>> describePersion(person) Description of jack age: 10 Occupation: camper >>> person1={'name':'jack','age':10} >>> describePersion(person1) Description of jack age: 10
>>> def describePersion(person): ... print 'Description of',person['name'] ... print 'age:',person['age'] ... try: ... print 'Occupation:'+person['occupation'] ... except KeyError:pass ... >>> >>> describePersion(person) Description of jack age: 10 Occupation:camper >>> describePersion(person1) Description of jack age: 10
try: obj.write except AttributeError: print "The object is not writeable" else: print 'The Object is writeable'