Python基础:异常处理

如何处理异常

  无论发生什么情况,finally block 中的语句都会被执行,哪怕前面的 try 和 excep block 中使用了 return 语句。
import sys
try:
    f = open('file.txt', 'r')
    #.... # some data processing
except OSError as err:
    print('OS error: {}'.format(err))
except:
    print('Unexpected error:', sys.exc_info()[0])
finally:
    f.close()
  假如不存在file.txt文件,则finally语句会抛出以下异常
Traceback (most recent call last):
  File ".\errorhandle.py", line 24, in <module>
    f.close()
NameError: name 'f' is not defined
  文件读写最好使用with open
import sys,os
inFile = 'file.txt'
if not os.path.exists(inFile):
    print(f'file {inFile} not exist')
    sys.exit()
with open(inFile, 'r') as fin:
    fin.read()

用户自定义异常

class MyInputError(Exception):
    """Exception raised when there're errors in input"""
    def __init__(self, value): # 自定义异常类型的初始化
        self.value = value
    def __str__(self): # 自定义异常类型的 string 表达形式
        return ("{} is invalid input".format(repr(self.value)))
    
try:
    raise MyInputError(1) # 抛出 MyInputError 这个异常
except MyInputError as err:
    print('error: {}'.format(err))

  执行代码块结果:

error: 1 is invalid input

 参考资料:

  极客时间《Python核心技术与实战》

猜你喜欢

转载自www.cnblogs.com/xiaoguanqiu/p/10936595.html