【问题标题】:Pass variable to an exception?将变量传递给异常?
【发布时间】:2023-03-15 13:50:01
【问题描述】:

我正在尝试学习 Python,我想知道是否可以将变量传递给 Exception?这是我的代码:

try:
    staffId = int(row['staffId'])
    openingSalary = int(row['initialSalary'])
    monthsWorked = float(row['monthsWorked'])
except CutomException:
    pass

class CustomException(ValueError): # raised if data conversion fails
    def __init__(self):
        print("There was a problem converting data")

我想将staffId 传递给异常,以便我可以打印如下内容:

print("工作人员 ID 转换数据时出现问题:", staffId)

我试过这个没有成功:How to pass a variable to an exception when raised and retrieve it when excepted?

【问题讨论】:

  • 您链接的问题的答案将满足您的需求(例如,在您的 try 块内调用 raise CustomException
  • 即使 try 块中没有错误,它不会引发 CustomException 吗?
  • 我在下面提供了一个答案来进一步说明。简而言之,您需要对raiseCustomException 进行条件化,以避免每次都引发异常。

标签: python exception


【解决方案1】:

我认为您应该在 except 块中而不是在异常类中处理异常。

try:
    raise CustomException(foo)
except CutomException as e:
    print(e.args)
    handle_exception()

class CustomException(Exception):
    def __init__(self, foo):
        super().__init__(foo, bar)

【讨论】:

    【解决方案2】:

    异常的调用者,例如raise 异常必须将参数传递给构造函数。

    class CustomException(ValueError): # raised if data conversion fails
        def __init__(self, message):
            self.message = message;
            print("There was a problem converting data")
    
    
    try:
        try:
            staffId = int(row['staffId'])
            openingSalary = int(row['initialSalary'])
            monthsWorked = float(row['monthsWorked'])
        except ValueError as e:
            raise CustomException(e);
    except CustomException:
        pass
    

    【讨论】:

    • 如何在 try...except 语句中做到这一点?在我的示例中,如果提供的信息不正确,假设您将字符串传递给 staffId,那么异常会自动引发。至少我是这么理解的。
    • @komodo 你可以用嵌套的异常来做,只要通过
    • 很好奇,Cutom 是否打算与 Custom 不同?
    【解决方案3】:

    自定义异常需要raise'd 有条件地由try 块包含staffId 变量。例如,当staffIdstr 而不是int

    try:
        # conditionalize a scenario where you'd want to raise an error
        #  (e.g. the variable is a string)
        if type(staffId) is str:
            raise CustomException(staffId)
        else:
            staffId = int(row['staffId'])
            openingSalary = int(row['initialSalary'])
            monthsWorked = float(row['monthsWorked'])
    except CutomException:
        pass
    
    class CustomException(ValueError): # raised if data conversion fails
        def __init__(self, id):
            print("There was a problem converting data %s" % id)
    

    【讨论】:

    • 问题是行中的所有信息都是字符串,因为它们来自提取到字典的 csv 文件。因此,我无法检查 staffId 是否为字符串,因为我已经知道它是。好主意;)
    • @komodo 我将其用作从您的评论到其他答案的条件。无论如何,我认为另一个答案有你所需要的。
    猜你喜欢
    • 2016-12-28
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 2011-10-01
    相关资源
    最近更新 更多