Python(三十三)——异常处理
异常处理:
是指程序在出现问题时依然可以正确的执行剩余的程序,而不会因为异常而终止程序执行。
Python中引进了很多用来描述和处理异常的类,称为异常类。
try:
pass
except 异常1:
pass
except 异常2:
pass
常见的异常说明:
SyntaxError:语法错误
NameError:尝试访问一个没有声明的变量
ZeroDivisonError:除零错误
ValueError:数值错误
TypeError:类型错误
AttributeError:访问对象的不存在属性
IndexError:索引越界异常
KeyError:字典关键字不存在
ArithmeticError:所有数值计算错误的基类
AssertionError:断言语句失败
BaseException:所有异常的基类
DeprecationtWarning:关于被遗弃的特征的警告
EnvirnmentError:浮点计数错误
EOFError:没有内建输入,到达EOF标记
ExceptionError:常规错误的基类
FutureWarning:关于构造将来语义会改变的警告
GeneratorExit:生成器发生异常通知退出
ImportError:导入模块、对象失败
traceback模块:
try:
a = 1/0
except BaseException as e:
print(e)
#division by zero
#没有使用,没有办法看到错误信息出现在第几行代码
import traceback
try:
a = 1/0
except:
traceback.print_exc()
'''
Traceback (most recent call last):
File "D:/untitled/chapter11.py", line 4, in <module>
a = 1/0
ZeroDivisionError: division by zero
'''
#输出了具体错了的信息
将错误信息保存到文件中:
import traceback
try:
a = 1/0
except:
with open('e.txt','a') as f:
traceback.print_exc(file=f)
自定义异常类,raise抛出异常
class AgeError(Exception): #继承Exception类
def __int__(self,age):
Exception.__init__(self)
self.age = age
def __str__(self):
return str(self.age)+'不在范围内'
if __name__ == '__main__':
age = 300
if 0<age<=100:
print('年龄正常')
else:
raise AgeError(age)