一、捕获异常

1、try  except

#!usr/bin/env python
# -*- coding:utf-8 -*-
num = input("请输入一个数字:")
try:
int_num = int(num) + 100
print(int_num)
except:
print("您输入的不是数字")

2、捕获具体的错误信息

AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的

异常类型

ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError 更多异常

更多异常

例如:

dic = ["wupeiqi", 'alex']
try:
dic[10]
except IndexError, e:
print e dic = {'k1':'v1'}
try:
dic['k20']
except KeyError, e:
print e s1 = 'hello'
try:
int(s1)
except ValueError, e:
print e

try except Exception as e

#!usr/bin/env python
# -*- coding:utf-8 -*-
num = input("请输入一个数字:")
try:
int_num = int(num) + 100
print(int_num)
except Exception as e: #Exception类所有异常都能捕获,是所有异常类的基类
print(e)

3、捕获多个异常

#!usr/bin/env python
# -*- coding:utf-8 -*-
num = input("请输入一个数字:")
try:
int_num = int(num) + 100
print(int_num)
except ValueError as e: #只捕获ValueError类型,捕获到后后面的except代码不再运行
print("发生ValueError")
except IndexError as e: #只捕获IndexError类型,捕获到后后面的except代码不再运行
print("发生IndexError")
except Exception as e: #捕获所有异常类型
print("发生Exception")

4、完整的异常结构

#!usr/bin/env python
# -*- coding:utf-8 -*-
try:
#要捕获异常的代码语句
pass
except ValueError as e:
#如果捕获到ValueError异常则执行本代码块
print(e)
except Exception as e:
#如果发生错误ValueError没有捕获到,则执行代码块
print(e)
else:
#如果try下的代码块没有异常则执行该代码块
print("未发生异常")
finally:
#不管发布发生错误都会执行该代码块
print("end")

5、可以自己抛出异常信息

#!usr/bin/env python
# -*- coding:utf-8 -*-
input_num = input("请输入一个大于0数字:")
try:
if int(input_num) <= 0:
raise Exception("数字不能小于等于0") #创建一个Exception对象
except Exception as e:
print(e)

上面代码中e为Exception的对象,print(e)为什么能打印出文本呢,其原理是利用__str__(self)特殊方法的:

#!usr/bin/env python
# -*- coding:utf-8 -*-
class Foo:
def __init__(self,ef):
self.ef = ef
def __str__(self):
return self.ef exception = Foo('出错了。。。。')
print(exception) #出错了。。。。,实际调用的是__str__(self)方法

6、断言

一般用于测试,assert 条件 ,如果条件成立执行,条件不成立直接抛出异常

#!usr/bin/env python
# -*- coding:utf-8 -*-
assert 2 == 2
assert 1 > 2 #因为条件不成立所以会直接抛异常

最新文章

  1. python嵌套函数、闭包与decorator
  2. [转] - 在mac的终端中使用sublime打开文件
  3. web服务器页面错误代码集
  4. js动态创建的元素绑定事件
  5. [PE结构分析] 8.输入表结构和输入地址表(IAT)
  6. java.lang.IllegalArgumentException: addChild: Child name &#39;/SSHE&#39; is not unique
  7. 使用Matrix控制图片和组件的变化
  8. LeetCode Bulls and Cows (简单题)
  9. 工作案件1 一切都是有check引起的
  10. Guava文档翻译之 Service
  11. A better way to learn D3 js - iLearning D3.js
  12. 下一代hadoop
  13. OpenStack Havana 部署在Ubuntu 12.04 Server 【OVS+GRE】(三)——计算节点的安装
  14. RecyclerView实例-实现可下拉刷新上拉加载更多并可切换线性流和瀑布流模式(1)
  15. [Mugeda HTML5技术教程之16]案例分析:制作跨屏互动游戏
  16. asp.net生成RSS
  17. JavaWeb(一)JSP基础组成
  18. Linux基础:xargs命令
  19. unable to auto-detect email address
  20. maven配置环境变量失败解决办法

热门文章

  1. 如何快速合并多个TXT文本内容
  2. 【数位DP】[LOJ10168] 恨7不成妻
  3. [NOIP2019模拟赛]夹缝
  4. Educational Codeforces Round49
  5. Android开发 输入法调用学习
  6. 【JZOJ3423】Vani和Cl2捉迷藏&amp;【BZOJ1143】祭祀river
  7. ElasticSearch _bulk批量处理报错The bulk request must be terminated by a newline
  8. 点击回退时需要点击2次才可返回js
  9. https,http和ssl的关系
  10. Java-MyBatis-MyBatis3-XML映射文件:insert, update 和 delete