码迷,mamicode.com
首页 > 编程语言 > 详细

[Python学习日记]Python的异常处理

时间:2015-07-20 01:21:41      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

一.异常

    Python遇到错误后会引发异常。若异常对象未被捕捉或处理,程序会回溯(traceback)来终止运行:

1 print 1 / 0
2 
3 Traceback (most recent call last):
4   File "D:\coding_file\python_file\TestPython\src\Test\test1.py", line 1, in <module>
5     print 1 / 0
6 ZeroDivisionError: integer division or modulo by zero

 

二.引发异常

    Python使用一个类或者实例参数调用raise语句来引发异常。

1 raise Exception("It‘s an exception raised by me.")
2 
3 Traceback (most recent call last):
4   File "D:\coding_file\python_file\TestPython\src\Test\test1.py", line 1, in <module>
5     raise Exception("It‘s an exception raised by me.")
6 Exception: Its an exception raised by me.

 

三:捕捉多个异常
    Python使用try/except来捕捉异常。可使用一个元组列出多种类型的异常来达到一个块捕捉多个类型异常的目的。

 1 try:
 2     x = input(Please enter the first number: )
 3     y = input(Please enter the second number: )
 4     print x / y
 5 except (ZeroDivisionError, TypeError) as e:
 6     print e
 7  
 8 输入:
 9 Please enter the first number: 1
10 Please enter the second number: 0
11 
12 运行结果:
13 integer division or modulo by zero
注:上面代码中的 except (ZeroDivisionError, TypeError) as e:
e用于存放异常信息,可用于随后的打印异常信息;在Python 3.0以前可写作except (ZeroDivisionError, TypeError), e:

四.要求用户重新输入
可使用循环语句,使的在发生错误时,程序不断要求重新输入:
 1 while True:
 2     try:
 3         x = input(Please enter the first number: )
 4         y = input(Please enter the second number: )
 5         result = x / y
 6         print x / y equals, result
 7     except (ZeroDivisionError, TypeError) as e:
 8         print Invalid input:, e
 9         print Please enter again.
10     else:
11         break
12 
13 输入:
14 Please enter the first number: 1
15 Please enter the second number: 0
16 
17 运行结果:
18 Invalid input: integer division or modulo by zero
19 Please enter again.
20 Please enter the first number: 
当没有发生异常时,程序正常退出(通过else:break语句)

五.发生异常后的清理
finally语句用于可能的异常后进行清理
 1 try:
 2     x = input(x = ?: )
 3     y = input(y = ?: )
 4     print x / y
 5 except (ZeroDivisionError, TypeError, NameError) as e:
 6     print e
 7 else:
 8     print No problem!
 9 finally:
10     print ‘Done!
在上面的代码中,不论try语句是否发生异常,finally子句肯定会被执行

 


 

[Python学习日记]Python的异常处理

标签:

原文地址:http://www.cnblogs.com/jzincnblogs/p/4660269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!