错误是多种多样的,在 except 语句中,可以捕获指定的异常

修改代码如下:

 1 import io
 2 
 3 path = r''
 4 mode = 'w'
 5 
 6 try:
 7     file = open(path,mode)
 8     str = file.read()
 9     print(str)
10 except FileNotFoundError as e:
11     print(e)
12 except io.UnsupportedOperation as e:
13     print(e)
14 finally:
15     print('end')

那么,现在只有在 path 和 mode 都正确的情况下,才会输出文件内容,而错误的话,则会输出错误的信息。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-01
  • 2021-08-23
  • 2021-11-16
  • 2021-09-26
猜你喜欢
  • 2021-10-05
  • 2021-05-19
  • 2022-12-23
  • 2021-12-15
  • 2021-06-04
  • 2021-06-15
相关资源
相似解决方案