[预定义函数中的RaiseError在我使用它定义另一个函数时被调用

问题描述 投票:0回答:1

我正在为一个大学项目工作,但遇到错误时遇到了麻烦。我应该创建几个函数,这些函数最终将在我将要创建的更多函数中重复使用。当使用某些特定参数时,我应该使用Raise ValueError。但是,当我使用初始函数定义新函数时,引发的ValueError是初始函数而不是新函数。

def first_function(arg1):
    if isinstance(arg1, tuple):
        return True
    else:
        raise ValueError("This is not a tuple")


def second_function(arg2):
    if first_function(arg2):
        print("That Is Indeed a Tuple")
    else:
        raise ValueError("This is really not a tuple")


argument = "(1, 1)"
print(second_function(argument))
# output: ValueError: This is not a tuple
# desired output: ValueError: This is really not a tuple

我该如何解决?我不应该重复代码。我应该继续重用自己构建的功能,但是错误似乎会干扰。

python
1个回答
0
投票

因此,从技术上讲,"This is not a tuple"错误运行正常。该错误将停止代码-发生错误的位置-并在该状态下在堆栈上报告。这是可取的。

也就是说,您可以使用try/except/finally捕获第一个错误并将其传递回第二个函数,这是我认为您要尝试的操作。

def first_function(arg1):
    if isinstance(arg1, tuple):
        return True
    else:
        raise ValueError("This is not a tuple")


def second_function(arg2):
    # The try statement wraps the if/then/else
    try: 
        # When you call first_function, it will error
        # That error will be recognized and passed to 
        # second_function's "except" statement
        if first_function(arg2):
            print("That Is Indeed a Tuple")
        # This else is probably not necessary
        # Since first_function will either work (return True), or
        #  raise an error, you will never have a situation where 
        # "if first_function(arg2):" will ever reach this else 
        # else:
        #    raise ValueError("This is not a tuple")
    except ValueError:
            raise ValueError("This is really not a tuple")


argument = "(1, 1)"
print(second_function(argument))

Traceback (most recent call last):
  File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 18, in second_function
    if first_function(arg2):
  File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 6, in first_function
    raise ValueError("This is not a tuple")
ValueError: This is not a tuple

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 27, in <module>
    print(second_function(argument))
  File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 23, in second_function
    raise ValueError("This is really not a tuple")
ValueError: This is really not a tuple

待用...

您通常试图用这种类型的设计模式实现的功能目标是避免像在first_function中那样进行检查(检查arg是否为元组)。

此设计模式通常是这样,您可以将错误检查留给主调用方法,并且所有被调用的方法都可以完成它们的工作-如果发送了错误的代码,则会引发错误。

def first_function(arg1):
    return arg1.append("I should be a list")


def second_function(arg2):
    try: 
        _list = first_function(arg2)
        print("arg2 is, indeed, a list")
    except Exception as e:
        raise ValueError("You did not pass a list (ORIG ERROR: {}".format(e))

argument = "(1, 1)"
print(second_function(argument))

输出:

Traceback (most recent call last):
  File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 7, in second_function
    _list = first_function(arg2)
  File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 2, in first_function
    arg1.append("I should be a list")
AttributeError: 'str' object has no attribute 'append'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 13, in <module>
    print(second_function(argument))
  File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 10, in second_function
    raise ValueError("You did not pass a list (ORIG ERROR: {}".format(e))
ValueError: You did not pass a list (ORIG ERROR: 'str' object has no attribute 'append'

在功能上,try/except/finally用于使错误静音。例如...

def first_function(_list, arg1):
    _list.append(int(arg1))
    return _list

def second_function():
    _list = []
    while True:
        arg2 = input("Enter an integer:")
        try: 
            _list = first_function(_list, arg2)
            print("a list containing {}".format(_list))
        except Exception as e:
            print ("You did not pass an integer. Try again")

second_function()

输出:

Enter an integer:1
a list containing [1]

Enter an integer:2
a list containing [1, 2]

Enter an integer:3
a list containing [1, 2, 3]

Enter an integer:r
You did not pass an integer. Try again

Enter an integer:4
a list containing [1, 2, 3, 4]
Enter an integer:
© www.soinside.com 2019 - 2024. All rights reserved.