1.raise语句
为了引发异常,可以使用一个类或者实例调用raise语句。
raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception
raise Exception('hyperdive overload')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: hyperdive overload
2.捕捉异常
try:
x=input()
y=input()
print x/y
except ZeroDivisionError:
print "The second number can't be zero"
2
0
The second number can't be zero
3.捕捉多个异常
上述代码只忽略了除数为0的异常,对于其他的异常,依然会出错
所以,我们可以再添加一个except语句,捕捉类型异常
try:
x=input()
y=input()
print x/y
except ZeroDivisionError:
print "The second number can't be zero"
except TypeError:
print "That wasn't a number..."
或者,在一个except语句里,多添加几个异常
try:
x=input()
y=input()
print x/y
except(ZeroDivisionError,TypeError,NameError):
print "Your numbers were bogus"
或者,异常全捕捉
try:
x=input()
y=input()
print x/y
except:
print "Something wrong happend..."
3.如果你希望程序继续运行,但是又想记录下错误,可以捕捉对象
try:
x=input()
y=input()
print x/y
except(ZeroDivisionError,TypeError,NameError),e:
print e
异常被打印,程序并没有报错
4.添加else字句,当不报错时,执行代码
while True: try: x=input() y=input() print x/y except: print "Invalid input.Please try again." else: break
在不报错的时候,退出循环