Python异常处理try...except、raise

https://www.cnblogs.com/Lival/p/6203111.html

一、try...except

有时候我们写程序的时候,会出现一些错误或异常,导致程序终止。例如,做除法时,除数为0,会引起一个ZeroDivisionError

例子:

1
2
3
4
a = 10
b = 0
c = a / b
print  "done"

运行结果:

Traceback (most recent call last):
File "C:/Users/lirong/PycharmProjects/untitled/openfile.py", line 3, in <module>
c=a/b
ZeroDivisionError: integer division or modulo by zero

我们发现程序因为ZeroDivisionError而中断了,语句print "done" 没有运行。为了处理异常,我们使用try...except,更改代码:

1
2
3
4
5
6
7
8
a = 10
b = 0
try :
     c = a / b
     print  c
except  ZeroDivisionError,e:
     print  e.message
print  "done"

  

运行结果:

integer division or modulo by zero
done

这样程序就不会因为异常而中断,从而print "done"语句正常执行。


try ....except...else 

当没有异常发生时,else中的语句将会被执行。

例子:

1
2
3
4
5
6
7
8
9
10
a = 10
b = 0
try :
     =  b /  a
     print  c
except  (IOError ,ZeroDivisionError),x:
     print  x
else :
     print  "no error"
print  "done"

运行结果:

0
no error
done


二、raise 引发一个异常

例子:如果输入的数据不是整数,则引发一个ValueError

1
2
3
4
5
inputValue = input ( "please input a int data :" )
if  type (inputValue)! = type ( 1 ):
     raise  ValueError
else :
     print  inputValue

假设输入1.2,运行结果为:

please input a int data :1.2
Traceback (most recent call last):
File "C:/Users/lirong/PycharmProjects/untitled/openfile.py", line 3, in <module>
raise ValueError
ValueError

如果输入1,运行结果为:

please input a int data :1
1


三、try ...finally 

无论异常是否发生,在程序结束前,finally中的语句都会被执行。

1
2
3
4
5
6
a = 10
b = 0
try :
     print  a / b
finally :
     print  "always excute"

猜你喜欢

转载自blog.csdn.net/qq_34638161/article/details/80784271