四.自定义函数(二)

1.错误处理

data=open('sketch.txt')

for each_line in data:

  try:

    (role,spoken_line)=each_line.split(':',1)

    print(role,end='')

    print('  said:',end='')

    print(spoken_line,end='')

  except:

    pass

data.close()

2.如果是文件被删除的情况,上面的代码处理不了,对其进行改进:

try:

  data=open('sketch.txt')

  try:

    for each_line in data:

      (role,spoken_line)=each_line.split(':',1)

      print(role,end='')

      print(' said:',end='')

      print(spoken_line,end='')

  except:

      pass

  data.close()

except:

  print('the data file is missing')

3.上面的异常处理太过一般化,可以特定指定异常,输出异常信息,优化代码如下:

try:

  data=open('sketch.txt')

  for each_line in data:

    try:

      (role,spoken_line)=each_line.split(':',1)

      print(role,end='')

      print(' said:',end='')

      pirnt(spoken_line,end='')

    except ValueError:

      pass

    data.close()

except IOError:

  print('the data file is missing')

原文地址:https://www.cnblogs.com/chenshaoping/p/7216832.html