原文链接
1.Python异常类
异常 | 描述 |
NameError | 尝试访问一个没有申明的变量 |
ZeroDivisionError | 除数为0 |
SyntaxError | 语法错误 |
IndexError | 索引超出序列范围 |
KeyError | 请求一个不存在的字典关键字 |
IOError | 输入输出错误(比如你要读的文件不存在) |
AttributeError | 尝试访问未知的对象属性 |
ValueError | 传给函数的参数类型不正确,比如给int()函数传入字符串形 |
2.捕获异常
- try:
-
try_suite - except
Exception1,Exception2,...,Argument: -
exception_suite - ......
#other exception block - else:
-
no_exceptions_detected_suite - finally:
-
always_execute_suite
2.1.try...except...语句
- try:
-
try_suite - except:
-
exception block
- try:
-
try_suite - except
Exception: -
exception block
- >>>
try: - ...
res = 2/0 - ...
except ZeroDivisionError: - ...
print "Error:Divisor must not be zero!" - ...
- Error:Divisor
must not be zero!
- try:
-
floatnum = float(raw_input("Please input a float:")) -
intnum = int(floatnum) -
print 100/intnum - except
ZeroDivisionError: -
print "Error:you must input a float num which is large or equal then 1!" - except
ValueError: -
print "Error:you must input a float num!" -
- [root@Cherish
tmp]# python test.py - Please
input a float:fjia - Error:you
must input a float num! - [root@Cherish
tmp]# python test.py - Please
input a float:0.9999 - Error:you
must input a float num which is large or equal then 1! - [root@Cherish
tmp]# python test.py - Please
input a float:25.091 - 4
- >>>
try: - ...
1/0 - ...
except ZeroDivisionError,reason: - ...
pass - ...
- >>>
type(reason) - 'exceptions.ZeroDivisionError'>
- >>>
print reason - integer
division or modulo by zero - >>>
reason - ZeroDivisionError('integer
division or modulo by zero',) - >>>
reason.__class__ - 'exceptions.ZeroDivisionError'>
- >>>
reason.__class__.__doc__ - 'Second
argument to a division or modulo operation was zero.' - >>>
reason.__class__.__name__ - 'ZeroDivisionError'
2.2try ... except...else语句
- >>>
import syslog - >>>
try: - ...
f = open("/root/test.py") - ...
except IOError,e: - ...
syslog.syslog(syslog.LOG_ERR,"%s"%e) - ...
else: - ...
syslog.syslog(syslog.LOG_INFO,"no exception caught\n") - ...
- >>>
f.close()
2.3 finally子句
例如2.2的例子,如果出现其他异常,无法捕获,程序异常退出,那么文件 f 就没有被正常关闭。这不是我们所希望看到的结果,但是如果我们把f.close语句放到finally语句中,无论是否有异常,都会正常关闭这个文件,岂不是很 妙
- >>>
import syslog - >>>
try: - ...
f = open("/root/test.py") - ...
except IOError,e: - ...
syslog.syslog(syslog.LOG_ERR,"%s"%e) - ...
else: - ...
syslog.syslog(syslog.LOG_INFO,"no exception caught\n") - ...
finally: - >>>
f.close()
3.两个特殊的处理异常的简便方法
3.1断言(assert)
- assert
expression[,reason]
- >>>
assert len('love') == len('like') - >>>
assert 1==1 - >>>
assert 1==2,"1 is not equal 2!" - Traceback
(most recent call last): -
File "", line 1, in - AssertionError:
1 is not equal 2!
- >>>
try: - ...
assert 1 == 2 , "1 is not equal 2!" - ...
except AssertionError,reason: - ...
print "%s:%s"%(reason.__class__.__name__,reason) - ...
- AssertionError:1
is not equal 2! - >>>
type(reason) - 'exceptions.AssertionError'>
3.2.上下文管理(with语句)
- with
context_expr [as var]: -
with_suite
- >>>
with open('/root/test.py') as f: - ...
for line in f: - ...
print line
file
decimal.Context
thread.LockType
threading.Lock
threading.RLock
threading.Condition
threading.Semaphore
threading.BoundedSemaphore
4.抛出异常(raise)
- raise
[SomeException [, args [,traceback]]
- >>>
raise NameError - Traceback
(most recent call last): -
File "", line 1, in - NameError
- >>>
raise NameError() #异常类的实例 - Traceback
(most recent call last): -
File "", line 1, in - NameError
- >>>
raise NameError,("There is a name error","in test.py") - Traceback
(most recent call last): -
File "", line 1, in - >>>
raise NameError("There is a name error","in test.py") #注意跟上面一个例子的区别 - Traceback
(most recent call last): -
File "", line 1, in - NameError:
('There is a name error', 'in test.py') - >>>
raise NameError,NameError("There is a name error","in test.py") #注意跟上面一个例子的区别 - Traceback
(most recent call last): -
File "", line 1, in - NameError:
('There is a name error', 'in test.py')
5.异常和sys模块
- >>>
try: - ...
1/0 - ...
except: - ...
import sys - ...
tuple = sys.exc_info() - ...
- >>>
print tuple - ('exceptions.ZeroDivisionError'>,
ZeroDivisionError('integer division or modulo by zero',), 0x7f538a318b48>) - >>>
for i in tuple: - ...
print i - ...
- 'exceptions.ZeroDivisionError'>
#异常类 - integer
division or modulo by zero #异常类的实例 - 0x7f538a318b48>
#跟踪记录对象