try:
...some functions...
except Exception, e:
print(e)
try:
...some functions...
except Exception as e:
print(e)
注意这里 Exception, e 变成了 Exception as e
>>> v
NameError: name 'v' is not defined
>>> v = 1/0
ZeroDivisionError: int division or modulo by zero
int int
SyntaxError: invalid syntax (#14>, line 1)
List = [2]
>>> List[3]
Traceback (most recent call last):
File "" , line 1, in
List[3]
IndexError: list index out of range
Dic = {'1':'yes', '2':'no'}
>>> Dic['3']
Traceback (most recent call last):
File "" , line 1, in <module>
Dic['3']
KeyError: '3'
>>> f = open('abc')
IOError: [Errno 2] No such file or directory: 'abc'
>>> class Worker:
def Work():
print("I am working")
>>> w = Worker()
>>> w.a
Traceback (most recent call last):
File "" , line 1, in
w.a
AttributeError: 'Worker' object has no attribute 'a'
>>> int('d')
Traceback (most recent call last):
File "" , line 1, in <module>
int('d')
ValueError: invalid literal for int() with base 10: 'd'
>>> iStr = '22'
>>> iVal = 22
>>> obj = iStr + iVal;
Traceback (most recent call last):
File "" , line 1, in
obj = iStr + iVal;
TypeError: Can't convert 'int' object to str implicitly
>>> assert 1 != 1
Traceback (most recent call last):
File "" , line 1, in <module>
assert 1 != 1
AssertionError
class Base(object):
def __init__(self):
pass
def action(self):
#抛出异常,说明该接口方法未实现
raise NotImplementedError
LookupError异常是IndexError、KeyError的基类, 如果你不确定数据类型是字典还是列表时,可以用LookupError捕获此异常
除StopIteration, GeneratorExit, KeyboardInterrupt 和SystemExit外,其他异常都是StandarError的子类。
错误检测与异常处理区别在于:错误检测是在正常的程序流中,处理不可预见问题的代码,例如一个调用操作未能成功结束。