一、按照自己的方式出错
1、raise语句
raise语句可以引发异常:
>>> raise Exception
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
raise Exception
Exception
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise Exception('hyperdrive overload')
Exception: hyperdrive overload
可以使用dir函数列出模块的内容:
>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning',
'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError',
'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning',
'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError',
'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',
'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
一些重要的内建异常类:
2、自定义异常类
自定义异常类只需要继承Exception类
>>> class SomeCustomException(Exception):pass
二、捕捉异常
捕捉异常使用try/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子句
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?"
四、用一个块捕捉两个异常
如果需要用一个块捕捉多个异常,那么可以将它们作为元祖列出:
try:
x=input('Enter the first number: ')
y=input('Enter the second number: ')
print x/y
except (ZeroDivisionError,TypeError,NameError):
print "Your number were bogus..."
五、捕捉对象
如果希望在except子句中访问异常对象本身,可以使用两个参数(注意,如果是捕捉到多个异常,需要向except子句提供一个参数——元祖。第二个参数e):
try:
x=input('Enter the first number: ')
y=input('Enter the second number: ')
print x/y
except (ZeroDivisionError,TypeError,),e:
print e
六、全捕捉
如果想捕捉所有异常,可以在except子句中忽略所有的异常类:
try:
x=input('Enter the first number: ')
y=input('Enter the second number: ')
print x/y
except:
print 'Something wrong happend...'
像上述捕捉异常是危险的,因为它会隐藏所有程序员为想到的并且未做好准备处理的错误。这时用except Exception, e会更好些,或者对异常对象e进行一些检查。
七、try/except加上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.
八、finally子句
x=None
try:
x=1/0
finally:
print 'Cleaning up....'
del x
finally子句肯定会执行,不管try子句中是否发生异常。
还可以和else一起使用:
try:
1/0
except NameError:
print "Unknown variable"
else:
print "That went well!"
finally:
print "Cleaning up"
九、异常和函数
如果异常在函数内引发而不处理,它就会传播至函数调用的地方。如果依旧没有被处理,就会继续传播,直到主程序。如果还没有被处理,程序会带着栈跟踪中止。
>>> def faulty():
raise Exception('Something is wrong')
>>> def ignore_exception():
faulty()
>>> def handle_exception():
try:
faulty()
except:
print 'Exception handled'
>>> ignore_exception()
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
ignore_exception()
File "<pyshell#5>", line 2, in ignore_exception
faulty()
File "<pyshell#2>", line 2, in faulty
raise Exception('Something is wrong')
Exception: Something is wrong
>>> handle_exception()
Exception handled