特定异常处理

2024-10-17 06:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,使用以下公式计算复利:p(1+I)n

从用户输入中获取本金、利息和年数

我编写了以下方法:

def is_valid_entries(principle, int_rate, years):
    try:
        #Convert the inputs from string to respective data type
        principal_float = float(principle)
        rate_float = float(int_rate)
        years_int = int(years)
        
        if not (0 < rate_float < 1.0):
            return False, "The interest rate must be between 0.00 to 1.00"

        return True, (principal_float, rate_float, years_int)
    except ValueError:
        return False, "Could not convert data to the appropriate data type"
    except:
        return False, "Unknown error"

然而,我的问题是,当我报告异常时,我希望非常具体。例如,如果本金有一个转换错误,我想报告在转换本金时有一个错误,利率和年限也遵循同样的逻辑。请让我知道如何在异常处理中做到这一点,或者是否有更好的方法来编写这篇文章


Tags: theto方法falseprincipaldatareturnrate
2条回答

通常,您必须将try块最小化到特定的行,以使其看起来像这样:

def is_valid_entries(principle, int_rate, years):
    #Convert the inputs from string to respective data type
    try:
        principal_float = float(principle)
    except ValueError:
        return False, "Could not convert principal to the appropriate data type"
    try:
        rate_float = float(int_rate)
    except ValueError:
        return False, "Could not convert rate to the appropriate data type"
    try:
        years_int = int(years)
    except ValueError:
        return False, "Could not convert years to the appropriate data type"
        
    if not (0 < rate_float < 1.0):
        return False, "The interest rate must be between 0.00 to 1.00"

    return True, (principal_float, rate_float, years_int)

当然,正如你所看到的,这很可怕。改进的提示是repeating code == functions,因此最好将其包装到函数中:

def number_conversion(string, type, name):
    try:
        return type(string)
    except ValueError:
        raise ValueError(f"Could not convert {name} to {type().__class__.__name__}")

现在,您的主代码可以如下所示:

def is_valid_entries(principle, int_rate, years):
    #Convert the inputs from string to respective data type
    try:
        principal_float = number_conversion(principle, float, "principle")
        rate_float = number_conversion(int_rate, float, "rate")
        years_int = number_conversion(years, int, "years")
    except ValueError as ve:
        return False, ve.message
        
    if not (0 < rate_float < 1.0):
        return False, "The interest rate must be between 0.00 to 1.00"

    return True, (principal_float, rate_float, years_int)

这样,您可以根据每个输入获得特定的消息

*删除空白^ {< CD3>},因为在代码

中没有其他异常出现。

你只是缺少了“提升”的关键词。你可能不想把整个事情都放在这样一个try块中,你只想在某些地方使用raise而不是return

例如,您有:

    if not (0 < rate_float < 1.0):
            return False, "The interest rate must be between 0.00 to 1.00"

你可以说:

    if not (0 < rate_float < 1.0):
            raise ValueError("The interest rate must be between 0.00 to 1.00")

这将引发以字符串形式返回的消息的值错误。如果有人在try块中调用您的函数,他们可以处理ValueError异常

https://docs.python.org/3/tutorial/errors.html

相关问题 更多 >