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 "<ipython-input-9-2aee0157c87b>", line 1, in <module>
raise Exception
Exception
###只抛出了异常类
>>raise Exception('异常值')
Traceback (most recent call last):
File "<ipython-input-10-54f75181d10a>", line 1, in <module>
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 "<ipython-input-27-c68afa428f2b>", line 14, in <module>
ignore_exception()
File "<ipython-input-27-c68afa428f2b>", line 5, in ignore_exception
faulty()
File "<ipython-input-27-c68afa428f2b>", 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 "<ipython-input-19-60d1e40b6850>", line 2, in <module>
1/0
ZeroDivisionError: division by zero
#捕获异常后,如果要继续引发它(即继续向上传播),可调用raise且不提供任何参数
try:
1/0
except ZeroDivisionError:
raise ValueError
Traceback (most recent call last):
File "<ipython-input-20-1646f08782cb>", line 5, in <module>
raise ValueError
ValueError
assert 表达式 [, 参数]
age = 10
>>assert 0<age<100
>>assert 0<age<100,''The age must be realistic'
#表达式为True,不返回任何信息
age = -1
>>assert 0<age<100
Traceback (most recent call last):
File "<ipython-input-25-76d3ffa0ff69>", line 1, in <module>
assert 0<age<100
AssertionError
>>assert 0<age<100,'The age must be realistic'
Traceback (most recent call last):
File "<ipython-input-26-19da6d03734e>", line 1, in <module>
assert 0<age<100,'The age must be realistic'
AssertionError: The age must be realistic