【问题标题】:Exception Handling: How to organize my code for specific question?异常处理:如何针对特定问题组织我的代码?
【发布时间】:2019-08-06 17:05:06
【问题描述】:

所以,我目前正在学习编程课程,我们开始学习文件和异常处理。我遇到了一个基于异常处理的问题。

这个问题要求我从population.txt 读取数据,检查以确保文件存在并且格式正确(如果它没有引发适当的异常),计算国家/地区的总人口文本文件并打印该总数。

文件是这样的

Afghanistan:32738376
Albania:3619778
Algeria:33769669
Jamaica:2804332
Japan:127288419
Paraguay:6831306
Peru:29180899
Philippines:92681453
Pitcairn Islands:48
Tajikistan:7211884
Turkmenistan:5179571
Zambia:11669534
Zimbabwe:12382920

我做了这样的事情。如您所见,我对如何组织代码感到困惑,但我知道我正在做某事。我应该把 if 语句放在 except 子句下吗?你们是怎么做到的?

try:
    infile=open("population..txt","r")
    for line in infile:
        line=line.rstrip()
        wordList=line.split(":")
        if type(word[0])!=str:
            raise ValueError("This is not a string")
        elif type(word[1])!=int:
            raise ValueError("This not an integer")
        else:
            pass
except IOError as e:
    print(e)
else:
finally:
    infile.close()

【问题讨论】:

    标签: python file exception


    【解决方案1】:

    需要在 try 块内引发异常才能被捕获。那部分代码是正确的。但是,您需要捕获所有可能引发的不同异常,并且在这种情况下,您绝对不需要自己引发它们:

    try:
        totpopulation = 0
    
        with open("population.txt","r") as infile:
            for line in infile:
                line=line.rstrip()
                wordList=line.split(":")
                popul = int(wordList[1])
                totpopulation += popul
        print("Total population:", totpopulation)
    
    except (OSError, ValueError, IndexError) as e:
        print(e)
    

    正如您在此处看到的,raise 语句未明确使用:当参数无效时,内置函数会引发异常:

    • 如果文件不存在,OSErroropen 引发的异常的类。
    • 如果字符串 wordList[1] 无法转换为整数,ValueErrorint(wordList[1]) 引发的异常的类。
    • 如果wordlist 的长度为0,则IndexErrorwordlist[1] 引发,因此索引超出范围。如果由于缺少':' 而未拆分行,则可能会发生这种情况。

    在我看来,您不需要此代码中的其他异常类。但是,如果您想知道还有哪些可用的异常,所有内置异常的列表都在 docs 中。

    【讨论】:

      【解决方案2】:

      您可以使用With Statement Context Managers 来避免从文件中读取数据时出现异常。

      with open('text_file', 'r') as f:
          # pass your code there
      

      【讨论】:

      • with 语句不会“避免”异常。如果出现问题,它们仍然会被提升,并且需要被抓住。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多