• 四.自定义函数(二)


    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')

  • 相关阅读:
    10.cocos2dx C++为Sprite添加触摸事件监听器
    9.多彩的幕布layer
    8.ZOrder
    7.cocos精灵创建和绘制
    6.cocos2d设置定时器
    5.cocos2d锚点
    4.cocos场景和层的调用
    文件导入导出
    两个整数相乘是否超限
    倒置字符串函数reverse
  • 原文地址:https://www.cnblogs.com/chenshaoping/p/7216832.html
Copyright © 2020-2023  润新知