一、Python异常的概念
异常:在程序执行过程中发生的影响程序正常执行的事件。当Python无法正常处理程序时就会发生异常,异常是Python对象,表示一个错误。 捕获异常:为了防止Python程序终止执行,当Python脚本发生异常时,需要捕获并处理它。
(1)Python内置异常:内部定义,自动识别
# 定义一个列表a=[1,2,3,4,"a",0,"12",6]for i in a:try: # 包含可能出现异常的代码print(i/3)except Exception as e: # 捕获try语句中的异常;Exception作为捕获到的异常类的对象print("出现异常:",e)else: # 未发生异常时执行的语句print("---OK---")finally: # 无论是否有异常,都会执行的语句print("---End---")

(2)自定义异常:
pwd=input("请输入密码:")
if len(pwd)<8:
ex=Exception("密码不能低于8位字符") # 定义异常(实例化的Exception对象:ex)
raise ex # 抛出异常
else:
print("密码长度ok")

二、常见Python异常类型
- FileNotFoundError:找不到指定文件的异常
- NameError:未声明or未初始化对象(没有属性)
- BaseException:所有异常的基类(父类),即包含所有的异常
三、异常处理语句
1. try…except…
- FileNotFoundError
#实现在当前脚本所在的目录下,打开所输入指定文件名的txt格式文本
#若能找到该文本则不会报错,若不能找到该文本则会抛出异常
try:
fileName = input("Please input fileName:")
open("%s.txt" %fileName)
except FileNotFoundError:
print("%s file not found" %fileName)
将以上脚本命名为Exception.py,在与该脚本相同的目录下新建一个txt文档命名为123.txt,运行该脚本
a.若输入想要打开的文本名字为123,则不会报错
b.若输入想要打开的文本名字为111,则会抛出异常
- NameError
#没有定义(or初始化)变量,直接打印
try:
print(stu)
except NameError:
print("stu not define")
输出结果:stu not define
#已定义(初始化)变量,直接打印
try:
stu = 'Harry'
print(stu)
except NameError:
print("stu not define")
输出结果:Harry
- BaseException
#没有定义(or初始化)变量,直接打印
try:
print(stu)
except BaseException:
print("stu not define")
输出结果:stu not define
除了以上可以对所抛出异常的信息进行自定义内容,也可以直接抛出系统本身保存的异信息,如下:
#没有定义(or初始化)变量,直接打印
try:
print(stu)
except NameError as msg:
print(msg)
输出结果:name 'stu' is not defined
2.try…except..else
1)若发生异常,则按照正常抛出异常信息
2)若未发生异常,则执行else其下的语句体
try:
# stu = "Jack"
print(stu)
except BaseException as msg:
print(msg)
else:
print("stu is defined")
输出结果:name 'stu' is not defined
try:
stu = "Jack"
print(stu)
except BaseException as msg:
print(msg)
else:
print("stu is defined")
输出结果:Jackstu is defined
3. try…except…finally
不管是否产生异常,都会执行finally其下的语句体
try:
# stu = "Jack"
print(stu)
except BaseException as msg:
print(msg)
else:
print("stu is defined")
finally:
print("The end")
输出结果:name 'stu' is not definedThe end
try:
stu = "Jack"
print(stu)
except BaseException as msg:
print(msg)
else:
print("stu is defined")
finally:
print("The end")
输出结果:Jackstu is definedThe end
4. raise 抛出异常
以上try语句是执行过程中捕获代码块的异常,而raise是通过事先定义一个条件,一旦符合异常条件就抛出异常
# 定义除法运算,抛出除数为0的异常
def division(x,y):
if y == 0:
raise ZeroDivisionError("Zero is not allowed!")
return x/y
# 传参调用
# 捕捉raise抛出的异常保存到msg变量中并打印
try:
division(8,0)
except BaseException as msg:
print(msg)
输出结果:Zero is not allowed!
PS:raise抛出异常只适用于python的标准异常类
作者:Fighting_001
链接:https://www.jianshu.com/p/60a3e87196ee
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
