python学习——异常处理

来源:互联网 发布:不懂英语能学编程吗 编辑:程序博客网 时间:2024/05/22 12:20

Python 使用 try...except 来处理异常,使用 raise 来引发异常。异常处理的执行过程与Java类似,可以配有finally,但异常处理中except和finally不能共存。A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.一个 try...except 块可以有一条 else 子句,就象 if 语句。如果在 try 块中没有异常引发,然后else子句被执行。

eg1:
try:
 1/0;
except Exception:
 print "an exception "

eg2:
try:
 1/0;
except Exception, e:
 print e

eg3:
try:
 x = input('Enter the first number: ')
 y = input('Enter the second number: ')
 print x/y
except (ZeroDivisionError, TypeError), e:
 print e

eg4:(不恰当的异常处理方式)
try:
 1/0
except Exception, e:
 print "divided by zero"
except ZeroDivisionError:
 print e

执行结果:
divided by zero

eg5:
try:
 1/0
except:
 print "divided by zero"

执行结果: 
divided by zero 

原创粉丝点击