博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python错误和异常
阅读量:6965 次
发布时间:2019-06-27

本文共 4064 字,大约阅读时间需要 13 分钟。

错误

从软件方面来说,错误是语法或是逻辑上的
语法错误指示软件的结构上有错误,导致不能被解释器解释或编译器无法编译,这些错误必须在程序执行前纠正
逻辑错误可能是由于不完整或是不合法的输入所致
还可能是逻辑无法生成,计算,或是输出结果需要的过程无法执行
 
简单的语法错误
>>> KeyboardInterrupt>>> abcdTraceback (most recent call last):  File "
", line 1, in
NameError: name 'abcd' is not defined>>> pass = 'qbcd' File "
", line 1 pass = 'qbcd' ^SyntaxError: invalid syntax

异常

当python检测到一个错误时,解释器就会指出当前流已经无法继续执行下去,这时候出现了异常
异常是因为程序出现了错误而在正常控制流以外采取的行为
这个行为又分为两个阶段,首先是引起异常发生的错误,然后是检测(和采取可能的措施)阶段
当程序运行时,因为遇到了未解的错误而导致终止运行,便会出现traceback消息,打印异常
异常
描述
NameError
未声明/初始化对象
IndexError
序列中没有此索引
SyntaxError
语法错误
KeyboardInterruupt
用户中断执行
EOFError
没有内建输入,达到EOF标记
IOError
输入/输出操作失败

try-except语句

定义了进行异常监控的一段代码,并且提供了处理异常的机制
语法:
try
 try_suite#监控这里的异常
except Exception【,reason】
 except_suite#异常处理代码
>>> try:...     f = open('foo.txt')...   File "
", line 3 ^SyntaxError: invalid syntax>>> try:... f = open('foo.txt')... except IOError:... print "No such file"... No such file
#!/usr/bin/env pythonimport timefor i in range(1,11):    print i    try:        time.sleep(0.5)    except KeyboardInterrupt:        passprint 'done'[root@bogon untitled10]# ./Ptime.py 1234^C5^C6^C78910done

捕获所有异常

#!/usr/bin/env pythonnum = ''result = ''try:    num = int(raw_input("please input some number:>"))    result = 100/numexcept:    print "some error"print result[root@bogon untitled10]# ./Aerror.py please input some number:>0some error[root@bogon untitled10]# ./Aerror.py please input some number:>asome error[root@bogon untitled10]# ./Aerror.py please input some number:>^Csome error[root@bogon untitled10]# ./Aerror.py please input some number:>some error

改进代码

#!/usr/bin/env pythonnum = ''result = ''try:    num = int(raw_input("please input some number:>"))    result = 100/numexcept (KeyboardInterrupt,EOFError):    print "\nuser cancelled"except (ValueError,ZeroDivisionError),e:    print "\nError" ,eprint result#!/usr/bin/env pythonnum = ''result = ''try:    num = int(raw_input("please input some number:>"))    result = 100/numexcept (KeyboardInterrupt,EOFError):    print "\nuser cancelled"except (ValueError,ZeroDivisionError),e:    print "\nError" ,eprint result

raise,自定义异常

>>> raise aaaTraceback (most recent call last):  File "
", line 1, in
NameError: name 'aaa' is not defined>>> raise ValueErrorTraceback (most recent call last): File "
", line 1, in
ValueError>>> raise ValueError ,'some error'Traceback (most recent call last): File "
", line 1, in
ValueError: some error
#!/usr/bin/env pythondef set_age(name,age):    if age < 1 or age > 150:        raise ValueError,"age out of range"    print "%s is %s year old" % (name,age)set_age('bob',-1)/usr/bin/python2.6 /root/PycharmProjects/untitled10/Prasie.pyTraceback (most recent call last):  File "/root/PycharmProjects/untitled10/Prasie.py", line 8, in 
set_age('bob',-1) File "/root/PycharmProjects/untitled10/Prasie.py", line 5, in set_age raise ValueError,"age out of range"ValueError: age out of rangeProcess finished with exit code 1

断言

断言是依据必须等价于布尔值为真的判定,此外发生异常也意味着表达式为假
#!/usr/bin/env pythondef set_age(name,age):    if age < 1 or age > 150:        raise ValueError,"age out of range"    print "%s is %s year old" % (name,age)def set_age2(name,age):    assert 0 < age <= 150,'Age out of range'    print "%s is %s year old" % (name,age)set_age('bob',20)set_age2('tom',200)/usr/bin/python2.6 /root/PycharmProjects/untitled10/Prasie.pybob is 20 year oldTraceback (most recent call last):  File "/root/PycharmProjects/untitled10/Prasie.py", line 13, in 
set_age2('tom',200) File "/root/PycharmProjects/untitled10/Prasie.py", line 9, in set_age2 assert 0 < age <= 150,'Age out of range'AssertionError: Age out of rangeProcess finished with exit code 1

 

转载于:https://www.cnblogs.com/weiwenbo/p/6626883.html

你可能感兴趣的文章
项目 08 WebSocket
查看>>
C# 模拟Http/Https请求框架类
查看>>
【记录】VMware解决网络找不到服务器的问题
查看>>
springmvc的过滤器和拦截器
查看>>
jQuery.each(object, [callback])数组对象操作--jQuery 对象访问 $().each(callback)
查看>>
树的存储结构 - 数据结构和算法41
查看>>
c3中基本动画
查看>>
按钮动画
查看>>
js练习题
查看>>
python ------- 文件处理之增删改查-------作业
查看>>
python 全栈 day03 计算机网络基础 -- 摘要
查看>>
类的一点点知识
查看>>
iOS - Swift Enumerations or how to annoy Tom
查看>>
Hibernate save()与persist()区别
查看>>
MongoDB给数据库创建用户
查看>>
linux下vim对于意外退出的文档的再次开启
查看>>
POJ 3683 2SAT
查看>>
如何替换B字段内包含A字段的那部分内容
查看>>
Objective-C Runtime 运行时
查看>>
常见的医学影像数据格式
查看>>