异常对象
Python 异常对象
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
上面的 ZeroDivisionError
就是一个异常类,相应的异常对象就是该类的实例。BaseException
类派生的,常见的异常类型可以在这里查看。
自定义异常
创建自定义的异常类需要从
# 自定义异常类
class SomeError(Exception):
pass
try:
x = input('Enter x: ')
y = input('Enter y: ')
print x / y
except ZeroDivisionError as e:
print 'ZeroDivisionError:',e
except TypeError as e:
print 'TypeError:',e
except BaseException as e:
print 'BaseException:',e
raise SomeError('invalid value') # 抛出自定义的异常
else:
print 'no error!'
print 'hello world'
运行上面代码,当
Enter x:
BaseException: unexpected EOF while parsing (<string>, line 0)
----------------------------------------------------------------------
SomeError Traceback (most recent call last)
<ipython-input-20-66060b472f91> in <module>()
12 except BaseException as e:
13 print 'BaseException:',e
---> 14 raise SomeError('invalid value')
15 else:
16 print 'no error!'
SomeError: invalid value