Python设计模式-异常
Python设计模式-异常处理详细操作教程
处理异常也是设计模式的主要标准。例外是在程序执行期间发生的错误。当发生特定错误时,生成异常非常重要。这有助于减少程序崩溃。
为什么要使用异常?
异常是在程序中处理错误和特殊条件的便捷方法。当用户认为指定的代码会产生错误时,使用异常处理很重要。
示例–除以零
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-22
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
输出
上面的程序生成以下输出-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-22
The entry is a
Oops! <class 'ValueError'> occured.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
引发异常
特别是在Python编程中,在运行时发生相应的代码错误时会引发异常。可以使用
" raise" 关键字来强制升高。
语法
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-22
raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt