输入为缺失值时的错误处理

Error handling when input is a missing value

我有这样的功能:

def get_output(input_number):
     output = max(7, min(12-0.7*input_number, 12)
     return output

我希望能够处理输入数字为 Nan 或 None 的错误。在这种情况下,应该向用户抛出自定义错误,即输入值不是数字,执行应该停止。

你可以“尝试”这个:

def get_output(input_number):
    try:
        float(input_number)
        output = max(7, min(12-0.7*input_number, 12)
        return output
    except:
        print("input_number is not a number")

我假设你在谈论 numpy NAN。

当您可以通过简单 if.

检查时,为什么要处理异常
import numpy as np

def get_output(input_number):
    if input_number is None or np.isnan(input_number):
        raise ValueError("Your message about incorrect value")
    output = max(7, min(12-0.7*input_number, 12)
    return output

这里有最简单的解决方案...

我建议这样做:

import numpy as np
class MyErr(Exception): pass

def get_output(input_number):
    if (not isinstance(input_number, (int, float)) or 
             np.isnan(input_number)):
        raise MyErr()
    return max(7, min(12-0.7*input_number, 12))

您可以通过两种方式实现。

  1. 无一例外 - 通过使用 * args

    def get_output(*args):
        if args[0]:
            output = max(7, min(12 - 0.7 * args[0], 12))
            return (output)
        else:
            print("the input value is not a number ")
    
    
    get_output(None)
    
  2. 使用 try except

    处理异常
def get_output(input_number):
    try:
        output = max(7, min(12 - 0.7 * input_number, 12))
    except TypeError:
        print("input value is not a number")
        return
    else:
        return output

get_output(None)