文章目录
- 一. 异常结构
- 1. try-except
- 2. try-except-else
- 3. try-except-else-finally
- 4. raise主动抛出异常(throw new)
- 5. 静默失败:pass
- 二. 自定义异常
每当发生让Python不知所措的错误时,它都会创建一个异常对象。如果你编写了处理该异常的代码,程序将继续运行;如果未对异常进行处理,程序将停止并显示traceback,其中包含有关异常的报告。
一. 异常结构
1. try-except
ZeroDivisionError异常例子
if__name__=='__main__':try:print(5/0)exceptZeroDivisionError:print("You can't divide by zero!")FileNotFoundError异常例子
filename='alice.txt'try:withopen(filename,encoding='utf-8')asf:contents=f.read()exceptFileNotFoundError:print(f"Sorry, the file{filename}does not exist.")2. try-except-else
通过将可能引发错误的代码放在try-except代码块中,可提高程序抵御错误的能力。依赖try代码块成功执行的代码都应放到else代码块中,如下:
if__name__=='__main__':filename='alice1.txt'try:withopen(filename,encoding='utf-8')asf:contents=f.read()exceptFileNotFoundError:# 这里并没有抛出异常print(f"Sorry, the file{filename}does not exist.")else:# 计算该文件大致包含多少个单词。words=contents.split()num_words=len(words)print(f"The file{filename}has about{num_words}words.")3. try-except-else-finally
finally块用于回收在try块里打开的物理资源,不管有没有异常,finally中的代码块总被执行。
try:num=int(input("请输入整数:"))result=8/numprint(result)exceptValueError:print("请输入正确的整数")exceptZeroDivisionError:print("除 0 错误")exceptExceptionasresult:print("未知错误 %s"%result)else:print("正常执行")finally:print("执行完成,但是不保证正确")4. raise主动抛出异常(throw new)
deffunctionName(level):iflevel<1:# 执行到这一句就会抛出这个异常raiseException("Invalid level!",level)# 触发异常后,后面的代码就不会再执行print("异常后不会执行啦!")functionName(0)5. 静默失败:pass
有时候你希望程序在发生异常时保持静默,就像什么都没有发生一样继续运行。
defcount_words(filename):"""计算一个文件大致包含多少个单词。"""try:--snip--exceptFileNotFoundError:passelse:--snip--filenames=['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']forfilenameinfilenames:count_words(filename)现在,出现FileNotFoundError异常时,将执行except代码块中的代码,但什么都不会发生。这种错误发生时,不会出现traceback,也没有任何输出。用户将看到存在的每个文件包含多少个单词,但没有任何迹象表明有一个文件未找到。
二. 自定义异常
自定义异常一般继承与Exception或BaseException。
classShortInputException(Exception):def__init__(self,length,least_length):super().__init__()self.length=length self.least_length=least_lengthdef__str__(self):return'您输入的长度为:{},最短长度为:{}'.format(self.length,self.least_length)try:content=input('请输入内容:')iflen(content)<5:raiseShortInputException(len(content),5)else:print('符合要求')exceptShortInputExceptionase:print(e)