python 异常类型----后期需理解调整
1.Python内建异常体系结构
The class hierarchy for built-in exceptions is:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
2.捕获异常的方式
方法一:捕获所有的异常
''' 捕获异常的第一种方式,捕获所有的异常 '''
try:
a = b
b = c
except Exception,data:
print Exception,":",data
'''输出:<type 'exceptions.Exception'> : local variable 'b' referenced before assignment ''
--------------------------------------------------------------------------------
方法二:采用traceback模块查看异常,需要导入traceback模块
''' 捕获异常的第二种方式,使用traceback查看异常 '''
try:
a = b
b = c
except:
print traceback.print_exc()
'''输出: Traceback (most recent call last):
File "test.py", line 20, in main
a = b
UnboundLocalError: local variable 'b' referenced before assignmen
--------------------------------------------------------------------------------
方法三:采用sys模块回溯最后的异常
''' 捕获异常的第三种方式,使用sys模块捕获异常 '''
try:
a = b
b = c
except:
info = sys.exc_info()
print info
print info[0]
print info[1]
'''输出:
(<type 'exceptions.UnboundLocalError'>, UnboundLocalError("local variable 'b' referenced before assignment",),
<traceback object at 0x00D243F0>)
<type 'exceptions.UnboundLocalError'>
local variable 'b' referenced before assignment
'''
-------------------------------------------------------------------------------
1、NameError:尝试访问一个未申明的变量
>>> v
NameError: name 'v' is not defined
2、ZeroDivisionError:除数为0
>>> v = 1/0
ZeroDivisionError: int division or modulo by zero
3、SyntaxError:语法错误
>>> int int
SyntaxError: invalid syntax (<pyshell#14>, line 1)
4、IndexError:索引超出范围
>>> List = [2]
>>> List[3]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
List[3]
IndexError: list index out of range
5、KeyError:字典关键字不存在
>>> Dic = {'1':'yes', '2':'no'}
>>> Dic['3']
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
Dic['3']
KeyError: '3'
6、IOError:输入输出错误
>>> f = open('abc')
IOError: [Errno 2] No such file or directory: 'abc'
7、AttributeError:访问未知对象属性
>>> class Worker:
def Work():
print("I am working")
>>> w = Worker()
>>> w.a
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
w.a
AttributeError: 'Worker' object has no attribute 'a'
8、ValueError:数值错误
>>> int('d')
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
int('d')
ValueError: invalid literal for int() with base 10: 'd'
9、TypeError:类型错误
>>> iStr = '22'
>>> iVal = 22
>>> obj = iStr + iVal;
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
obj = iStr + iVal;
TypeError: Can't convert 'int' object to str implicitly
10、AssertionError:断言错误
>>> assert 1 != 1
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
assert 1 != 1
AssertionError
11、MemoryError:内存耗尽异常
12、NotImplementedError:方法没实现引起的异常
示例:

1 class Base(object):
2 def __init__(self):
3 pass
4
5 def action(self):
6 raise NotImplementedError

定义一个类,一个接口方法action,如果直接调用action则抛NotImplementedError异常,这样做的目的通常是用来模拟接口
13、LookupError:键、值不存在引发的异常
LookupError异常是IndexError、KeyError的基类
如果你不确定数据类型是字典还是列表时,可以用LookupError捕获此异常
14、StandardError 标准异常。
除StopIteration, GeneratorExit, KeyboardInterrupt 和SystemExit外,其他异常都是StandarError的子类。
异常处理有别于错误检测:
错误检测与异常处理区别在于:错误检测是在正常的程序流中,处理不可预见问题的代码,例如一个调用操作未能成功结束
python 异常类型----后期需理解调整的更多相关文章
- Python异常类型及包含关系
Python异常类型及包含关系,设计异常捕获时参考: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- ...
- Python异常类型及处理、自定义异常类型、断言
异常的概念.识别报错信息 异常处理 断言的基本使用 异常类型(异常就是报错) 常见异常 NameError:名称错误 SyntaxError:语法错误 TypeError:类型错误 错误回溯 查看报错 ...
- python 异常类型
1.NameError:尝试访问一个未申明的变量>>> vNameError: name 'v' is not defined 2.ZeroDivisionError:除数为0&g ...
- 【python】python异常类型
python2: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- Stop ...
- python异常类型
python2: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- Stop ...
- python 异常类型大全
try except 处理异常真舒服!!!
- 第二百九十九节,python操作redis缓存-SortSet有序集合类型,可以理解为有序列表
python操作redis缓存-SortSet有序集合类型,可以理解为有序列表 有序集合,在集合的基础上,为每元素排序:元素的排序需要根据另外一个值来进行比较,所以,对于有序集合,每一个元素有两个值, ...
- 第二百九十八节,python操作redis缓存-Set集合类型,可以理解为不能有重复元素的列表
python操作redis缓存-Set集合类型,可以理解为不能有重复元素的列表 sadd(name,values)name对应的集合中添加元素 #!/usr/bin/env python # -*- ...
- 第二百九十七节,python操作redis缓存-List类型,可以理解为列表
python操作redis缓存-List类型,可以理解为列表,是可以有重复元素的列表 List操作,redis中的List在在内存中按照一个name对应一个List来存储.如图: lpush(name ...
随机推荐
- poj2892
题解: 答案=后缀-前缀-1 如果被轰了,那么就时0 在一开始加入0,n+1,保证有前缀后缀 代码: #include<cstdio> #include<cmath> #inc ...
- Flask初级(十一)flash与APScheduler 实现定时任务
from flask import Flask from flask_apscheduler import APScheduler # 引入APScheduler class Config(objec ...
- 搜索评价指标——NDCG
◆版权声明:本文出自胖喵~的博客,转载必须注明出处. 转载请注明出处:https://www.cnblogs.com/by-dream/p/9403984.html 概念 NDCG,Normali ...
- DevExpress WPF入门指南:Smart Tag扩展功能
Smart Tag提供了一些扩展功能用于简化指定某些属性的程序,比如下面这几项: Application Theme Data Context Image Gallery Convert to DXW ...
- 深入理解Linux网络技术内幕——用户空间与内核空间交互
概述: 内核空间与用户空间经常需要进行交互.举个例子:当用户空间使用一些配置命令如ifconfig或route时,内核处理程序就要响应这些处理请求. 用户空间与内核有多种交互方式,最常 ...
- OSI七层网络模型与TCP/IP四层模型介绍
目录 OSI七层网络模型与TCP/IP四层模型介绍 1.OSI七层网络模型介绍 2.TCP/IP四层网络模型介绍 3.各层对应的协议 4.OSI七层和TCP/IP四层的区别 5.交换机工作在OSI的哪 ...
- windows form参数传递过程
三.windows form参数传递过程 在Windows 程序设计中参数的传递,同样也是非常的重要的. 这里主要是通过带有参数的构造函数来实现的, 说明:Form1为主窗体,包含控件:文本框text ...
- ZOJ 17届校赛 Knuth-Morris-Pratt Algorithm( 水题)
In computer science, the Knuth-Morris-Pratt string searching algorithm (or KMP algorithm) searches f ...
- HslControls组件库 工业控件库 曲线控件 时间控件 管道控件 温度计控件 阀门控件 传送带控件 进度条控件 电池控件 数码管控件等等
本篇博客主要对 HslControls 组件做一个大概的总览介绍,更详细的内容可以参照页面里的子链接,还有github上的源代码,然后进行相关的学习,和使用. Prepare 先从nuget下载到组件 ...
- 新手小白Linux(Centos6.5)部署java web项目(mysql5.7安装及相关操作)
一.安装 参考:https://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html # 检测系统中是否安装了mysql y ...