这篇博客主要是阅读python之旅 时做的笔记。提取出最主要的知识点,供个人在以后中快速查阅。
常见组合
try...except...
try...except...else...
try...except...else...finally...
try...except...except...else...finally...
try...finally...
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
else: # 当没有异常时,执行else
print 'no error!'
因为BaseException是所有异常的父类。
- Finally
try:
x = 1/0
print x
finally: # 不管三七二十一,这个都要执行
print 'DONE'
raise异常
有时候捕获了异常,还想再把异常抛出去。
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 # 使用 raise 抛出异常,不用带参数
else:
print 'no error!'
print 'hello world'
Exception类 — 自定义异常类
# 自定义异常类
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