try:
#引发异常的代码
excep (异常类1,异常类2,...,异常类n) as 异常值:
#捕作异常后,执行此语句块,没捕作到向上传播,直到主程序终止并显示跟踪消息
else:
#try下语句块没有异常错误,执行此语句块
finally:
#不管有没有引发异常,ecpect有没有捕作到异常,都执行此语句块
不能有try....else...组合,其它都行
except Exception : #这表示能捕捉到Exception及其派生子类的异常
except: #这表示能捕捉到所有异常
raise
>>raise Exception
Traceback (most recent call last):
File "", line 1, in
raise Exception
Exception
###只抛出了异常类
>>raise Exception('异常值')
Traceback (most recent call last):
File "", line 1, in
raise Exception('异常值')
Exception: 异常值
#有异常类,也有值
def faulty():
raise Exception('Something is wrong')
def ignore_exception():
faulty()
def handle_exception():
try:
faulty()
except:
print('Exception handled')
>>ignore_exception()
Traceback (most recent call last):
File "", line 14, in
ignore_exception()
File "", line 5, in ignore_exception
faulty()
File "", line 2, in faulty
raise Exception('Something is wrong')
Exception: Something is wrong
>>handle_exception()
Exception handled
#faulty中引发的异常依次从faulty和ignore_exception向外传播,最终显示一条跟踪消息。
#调用handle_exception时,异常最终传播到handle_exception,并被这里的try/except语句处理
try:
1/0
except ZeroDivisionError:
raise
Traceback (most recent call last):
File "", line 2, in
1/0
ZeroDivisionError: division by zero
#捕获异常后,如果要继续引发它(即继续向上传播),可调用raise且不提供任何参数
try:
1/0
except ZeroDivisionError:
raise ValueError
Traceback (most recent call last):
File "", line 5, in
raise ValueError
ValueError
assert 表达式 [, 参数]
age = 10
>>assert 0>assert 0>assert 0", line 1, in
assert 0>assert 0", line 1, in
assert 0