【问题标题】:How to work with try and except in python?如何在 python 中使用 try 和 except?
【发布时间】:2020-05-28 10:13:30
【问题描述】:

该程序必须分析学生编号,如果正确,则将其写入一个list,如果不正确,则将其写入另一个list。如果它们有八位数字并且只包含数字,则它们是正确的。

但是,当涉及到 tryexcept 部分时,我不知道该输入什么。

如果有人可以提供帮助,我将不胜感激!

Valid_file = "ValidNumbers.txt"
Invalid_file = "InvalidNumbers.txt"
Data_file = "Data.txt"

def analyse_students(Data_file):
    lenth = len(Data_file)
    total = 0
    try:
    
    except: 
    
    return 0
    
def read(Data_file):
    count = 0
    student_list = []
    try:
        open(Data_file)
    except:
        print("Couldn't append file", Valid_file)
    return count, student_list

def write(student, status):
    if status:
        try:
            open(Data_file)
        except:
            print("Couldn't append file", Invalid_file)
    
count, student_list = read(Data_file)

print("Number of lines read", count)

for student in student_list:

    print("See output files")

【问题讨论】:

  • 你是什么意思i however have no idea what to type when it comes to the try except part
  • 你遇到了什么错误?语法错误 try-except 还是没有得到想要的结果?
  • 我没有收到错误它什么也不做。我只是不知道要输入什么才能使程序正常工作。 data_file 包含我需要排序的一组数字,但我不知道如何测试,以便可以将这些数字发送到它们各自的列表。
  • 您需要使用上下文管理器才能写入或打开文件。

标签: python try-catch except


【解决方案1】:

好的,所以有几件事需要在哪里解释。

try-except 是做什么用的?

它用于捕获程序引发的错误。任何可能引发异常的代码都插入到 try 语句中,在该语句下方,任何数量的 except 语句都带有您想要捕获的任何单个错误。

try:
    user_input = int(input('Give me a number: '))
except ValueError:
    print('That is not a number!')

什么时候应该使用 try-except?

在可能引发错误的每一行代码上都使用try-except 不是一个好习惯,因为这可能是错误的一半或更多。那么什么时候使用呢?很简单,问这个问题:我想在引发该错误的情况下执行任何自定义操作吗?如果答案是,那么您就可以开始了。

捕捉Exception 或空except

正如我在您的示例中看到的,您使用的是空的except。使用空的except 语句将捕获包围代码引发的每一个错误,这与捕获Exception 相似(但不相同)。 Exception 类是 Python 环境中每个非系统退出 (read here) 的内置异常的超类,使用 except:Exception 捕获所有异常通常是一种不好的做法与except Exception:为什么?因为你没有让用户(甚至你,程序员)知道你正在处理什么错误。例如:

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except Exception:
    print('Error!')
    # But wait, are you catching ValueError because the user did not input a number, 
    # or are you catching IndexError because he selected an out of bound array index? 
    # You don't know  

捕获多个异常

基于前面的示例,您可以使用多个try-except 语句来区分引发了哪些错误。

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except ValueError:
    print('That is not a number')
except IndexError:
    print('That fruit number does not exist!')  

分组例外

如果您想将两个特定的例外用于同一目的,您可以将它们分组到tuple

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except (ValueError, IndexError):
    print('Invalid selection!')  

你的情况

根据此信息,将这些 try-except 块添加到您的代码中,并查看在其执行过程中可能引发的错误,并询问之前推荐的问题 我是否要针对此错误执行一些自定义操作?

另外

  • try-except-else 语句。见here
  • try-except-finally 语句。见here
  • 您可以将它们全部组合到try-except1-except2...exceptN-else-finally 语句中。
  • 我建议您熟悉内置错误,为什么要这样做!

【讨论】:

    【解决方案2】:

    我是这样理解的:

    您想将正确的学生编号附加到list,如果错误,请将它们附加到另一个list。检查学生的数字是否正确的方法是它们是否是包含8位数字的数字。

    假设您的代码中的student 指的是学生人数:(使用for loop 遍历学生列表。我已尝试解决您的主要问题:try and except

    def analyse_students(Data_file):
        lenth = len(Data_file)
        total = 0
        try:
            if len(str(student)) == 8 and student in "1234567890":
                #append to a list(correct ones)
            elif not(lenth == 8 and Data_file in "1234567890"):
                #append to another list(wrong ones)  
            else:
                raise ValueError
    
        except Exception:
            #print something
    
        return 0
    

    try 捕获所有错误,except 捕获它们。因此,我们可以自己 raise 一个错误(这里说 ValueError),try 也会捕获它并将其发送到将打印错误消息的 except 块。

    raise 关键字引发异常。

    您可以定义raise 的错误类型,以及要打印给用户的文本。

    希望这对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2016-04-06
      • 2012-11-06
      • 1970-01-01
      • 2013-06-03
      • 2021-04-24
      相关资源
      最近更新 更多