-
错误
-
异常
异常类型 | 描述 | 简单例子 | ||
NameError | 尝试访问一个未声明的变量,或者是在名称空间中不存在的变量 |
|
||
ZeroDivisionError | 除数为零 |
|
||
SyntaxError |
|
|||
IndexError | 请求的索引走出序列范围 |
|
||
KeyError | 请求一个不存在的字典关键字 |
|
||
IOError |
|
|||
AttributeError | 尝试访问未知的对象属性 |
|
-
语法
1
2
3
4
|
try
:
try_suite
#监测这里的异常
except
Exception[, reason]:
except_suit
#异常处理代码
|
1
2
3
4
|
>>> f
=
open
(
'xpleaf'
)
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
IOError: [Errno
2
] No such
file
or
directory:
'xpleaf'
|
1
|
[Errno
2
] No such
file
or
directory:
'xpleaf'
|
1
2
3
4
5
6
|
>>>
try
:
... f
=
open
(
'xpleaf'
,
'r'
)
...
except
IOError, e:
...
print
'could not open file:'
, e
...
could
not
open
file
: [Errno
2
] No such
file
or
directory:
'xpleaf'
|
-
语法
1
2
3
4
5
6
|
try
:
try_suite
except
Exception1[, reason1]:
suite_for_exception_Exception1
except
Exception2[, reason2]:
suite_for_exception_Exception2
|
-
语法
1
2
3
4
|
try
:
try_suite
except
(Exception1, Exception2)[, reason1]:
suite_for_exception_Exception1_and_Exception2
|
|
1
2
3
4
5
|
BaseException
-
KeyboardInterrupt
-
SystemExit
-
Exception
-
(
all
other current built
-
in
exceptions)
|
-
使用Exception:无法捕获KeyboardInterrupt
1
2
3
4
|
try
:
name
=
raw_input
(
'Your name:'
)
except
Exception:
print
'quit'
|
1
2
3
4
5
|
/usr/bin/python2
.7
/home/xpleaf/PycharmProjects/Python_book/10/test
.py
Your name:Traceback (most recent call last):
File
"/home/xpleaf/PycharmProjects/Python_book/10/test.py"
, line 3,
in
<module>
name = raw_input(
'Your name:'
)
KeyboardInterrupt
|
-
使用BaseException:捕获所有异常(错误与非错误条件引起的)
1
2
3
4
|
try
:
name
=
raw_input
(
'Your name:'
)
except
BaseException:
print
'quit'
|
1
2
|
/usr/bin/python2
.7
/home/xpleaf/PycharmProjects/Python_book/10/test
.py
Your name:quit
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
>>>
try
:
...
float
(
'foo'
)
...
except
ValueError, e:
...
print
'Error Happen:'
, e
...
Error Happen: could
not
convert string to
float
: foo
>>>
>>>
type
(e)
<
type
'exceptions.ValueError'
>
>>>
str
(e)
'could not convert string to float: foo'
>>>
print
e
could
not
convert string to
float
: foo
>>> e.__class__
<
type
'exceptions.ValueError'
>
>>> e.__class__.__name__
'ValueError'
>>> e
ValueError(
'could not convert string to float: foo'
,)
|
-
异常引发时,如果使用错误原因变量,实际上,这是一个包含来自导致异常的诊断信息的类实例,异常参数自身会组成一个元组,并存储为这个异常类的属性
-
异常参数是该异常发生时传递给异常处理器的一个字符串对象,它会成为这个异常类的实例的一个属性,并且可以通过调用str()来获得该诊断信息(使用print语句,实际也是调用了该str()方法)
|
1
2
3
4
5
6
7
8
9
|
>>>
try
:
...
float
(
4
)
...
except
(ValueError, TypeError), e:
...
print
'Error Happen:'
, e
...
else
:
...
print
'No Exceptions'
...
4.0
No Exceptions
|
-
try-except-finally
1
2
3
4
5
6
|
try
:
A
except
Exception1, e:
B
finally
:
C
|
-
try-except-else-finally
1
2
3
4
5
6
7
8
|
try
:
A
except
Exception1, e:
B
else
:
C
finally
:
D
|
1
2
3
4
5
6
7
|
>>> with
open
(
'xpleaf.txt'
,
'r'
) as f:
...
for
eachLine
in
f:
...
print
eachLine
...
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
IOError: [Errno
2
] No such
file
or
directory:
'xpleaf.txt'
|
-
语法
1
|
raise
[SomeException [, args [, traceback]]]
|
raise语句的用法 |
|
raise语法 | 描述 |
raise exclass | 触发一个异常,从cxclass生成一个实例(不含任何异常参数) |
raise exclass() | 同上,但现在不是类;通过函数调用操作符(其实就是指加上了`()`)作用于类生成一个新的exclass实例,同样也没有异常参数 |
raise exclass, args | 同上,但同时提供的异常参数args,可以是一个参数也可以是元组 |
raise exclass(args) | 同上 |
raise exclass, args, tb | 同上,但提供一个跟踪记录(traceback)对象tb供使用 |
raise exclass, instance | 通过实例触发异常(通常是exclass的实例);如果实例是exclass的子类实例,那么这个新异常的类型会是子类的类型(而不是exclass);如果实例既不是exclass的实例也不是exclass子类的实例,那么会复制此实例为异常参数去生成一个新的exclass实例 |
raise instance |
通过实例触发异常:异常类型是实例的类型;等价于raise instance.__class__, instance(同上) |
raise | 重新触发前一个异常,如果之前没有异常,触发TypeError |
-
raise exclass
1
2
3
4
|
>>>
raise
ValueError
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
ValueError
|
-
raise exclass()
1
2
3
4
|
>>>
raise
ValueError()
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
ValueError
|
-
raise exclass, args
1
2
3
4
5
6
7
8
9
|
>>>
raise
ValueError,
'Something wrong happen about value'
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
ValueError: Something wrong happen about value
>>>
>>>
raise
ValueError, (
'New Error'
,
'Something wrong happen about value'
)
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
ValueError: (
'New Error'
,
'Something wrong happen about value'
)
|
-
raise exclass(args)
1
2
3
4
|
>>>
raise
ValueError(
'Something wrong happen about value'
)
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
ValueError: Something wrong happen about value
|
-
raise exclass, instance
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> newError
=
ValueError(
'Something wrong happen about value'
)
>>>
raise
ValueError, newError
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
ValueError: Something wrong happen about value
>>>
>>> newError
=
ValueError(
'Something wrong happen about value'
)
>>>
raise
IOError, newError
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
IOError: Something wrong happen about value
# 注意看异常类型和异常参数
|
-
raise instance
1
2
3
4
5
6
7
8
9
10
|
>>> newError
=
ValueError(
'Something wrong happen about value'
)
>>>
raise
newError
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
ValueError: Something wrong happen about value
>>>
>>>
raise
newError.__class__, newError
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
ValueError: Something wrong happen about value
|
-
raise
1
2
3
4
5
|
>>>
raise
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
TypeError: exceptions must be old
-
style classes
or
derived
from
BaseException,
not
NoneType
# 即达不到所描述的效果,即使前面已经有异常出现,还是会触发TypeError异常
|
-
语法
1
|
assert
expression[, arguments]
|
1
2
3
4
5
6
7
8
9
10
|
>>>
assert
1
=
=
1
>>>
assert
1
=
=
0
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
AssertionError
>>>
>>>
assert
1
=
=
0
,
'One does not equal zero silly!'
Traceback (most recent call last):
File
"<stdin>"
, line
1
,
in
<module>
AssertionError: One does
not
equal zero silly!
|
-
SystemExit
-
KeyboardInterrupt
-
Exception
1
2
3
4
5
6
7
8
|
>>>
try
:
...
float
(
'abc123'
)
...
except
:
...
import
sys
... exc_tuple
=
sys.exc_info()
...
>>>
print
exc_tuple
(<
type
'exceptions.ValueError'
>, ValueError(
'could not convert string to float: abc123'
,), <traceback
object
at
0x7f9ba0fa0f38
>)
|
-
exc_type:异常类
-
exc_value:异常类的实例
-
exc_traceback:跟踪记录对象
异常相关的标准库 |
|
模块 | 描述 |
exceptions | 内建异常(不需要导入这个模块) |
contextlib | 为使用with语句的上下文对象工具 |
sys | 主要是sys.exc_info() |