处理多个相同类型的异常并在python中恢复执行 [英] Handing multiple exception of same type and resume execution in python

查看:105
本文介绍了处理多个相同类型的异常并在python中恢复执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎一旦您提出了Python中用户定义的异常,就无法恢复测试的执行。但是在我的场景中,我想检查不同输入值发生的错误。但是,当前的实现方式限制了继续对不同输入向量进行检查错误。

It appears that one cannot resume the execution of test once you hit the raise the user defined exception in Python. But in my scenario I want to check error occurred for different input values. But Current implementation is restricting to continue the check error for the different input vectors.

但是,在提出某种复杂的解决方案之前,我想问专家,看看是否有我所缺少的东西。 不幸的是,如果不进行大量重构,我将无法轻松更改此范例

However, before coming up with some sort of convoluted solution to my problem, I figured I would ask the experts and see if there is something I'm missing. Unfortunately, I cannot change this paradigm easily without significant re-factoring.

我的应用程序类似于:


  • 输入将作为numGen函数给出。此numGen函数将输入添加到随机数。在我的示例中,我正在检查10个不同的随机数。

  • 注意输入也将有所变化,并且随机数生成的范围也会发生变化

问题陈述:


  • 我想检查每个输入是否发生错误,是否发生任何错误,引发异常并存储哪个输入的信息

  • I want to check for each input whether error is occurred and if any error occurred raise exception and store the information of which input

也继续执行其他输入的程序,但是在我的实现中,我无法继续执行。

Continue the program execution for other input as well, But In my implementation it I'm not able to continue further execution.

问题:


  • 如何稍后在不使用unittest模块的情况下引发异常?

来自随机进口randint

from random import randint

class RND_ERROR(Exception):
    def __init__(self, ErrNum, *arg, **kwargs):
        self.RND_ERR_NR = int(ErrNum)
        self.RND_ERR_MSG = ""         
        if self.RND_ERR_NR == 0x00000000:
            self.RND_ERR_MSG = "NO ERROR"
        elif self.RND_ERR_NR == 0x00000001:
            self.RND_ERR_MSG = "RANDOM NUMBER IS ONE"
        elif self.RND_ERR_NR == 0x00000002:
            self.RND_ERR_MSG = "RANDOM NUMBER IS TWO"
        elif self.RND_ERR_NR == 0x00000003:
            self.RND_ERR_MSG = "RANDOM NUMBER IS THREE"
        else:
            self.RND_ERR_MSG = "RANDOM NUMBER GREATER THAN THREE"
    def __str__(self):
        return "RND ERROR (0x%08X): %s" % (self.RND_ERR_NR,self.RND_ERR_MSG)

    def __repr__(self):
       return self.__str__()

def check_error(b):
    print "dict",b
    count = 0

    for i, error_nr in b.items():

        error_nr = error_nr % 2
        print "key:val",i, error_nr
        if error_nr ==0:
            count = count +1
            # print count
        elif error_nr > 0:

            # print error_nr
            raise RND_ERROR(error_nr)

def numGen(input):
    from random import randint
    result= {}
    for i in range(9):
        j = (randint(0,4))
        result[i] = input+j
        result.update()
    check_error(result)

if __name__ == '__main__':
    try:
        numGen(3)
    except BaseException as e:
        print e

Output1: # Since at the 6th input error occurred and execution stopped **(Some what Best case)**  
dict {0: 6, 1: 6, 2: 6, 3: 6, 4: 4, 5: 6, 6: 3, 7: 3, 8: 7}
key:val 0 0
key:val 1 0
key:val 2 0
key:val 3 0
key:val 4 0
key:val 5 0
key:val 6 1
RND ERROR (0x00000001): RANDOM NUMBER IS ONE

**Output2:**
dict {0: 7, 1: 6, 2: 4, 3: 3, 4: 6, 5: 6, 6: 7, 7: 5, 8: 4}
key:val 0 1

RND ERROR (0x00000001): RANDOM NUMBER IS ONE

Expected Output:

Input1 - Pass
Input2 - Pass
Input3 - Pass
Input4 - Pass
Input5 - Pass
Input6 - RANDOM IS TWO (exception occurred)
Input7 - Pass  # execution continued for next input check
Input8 - Pass
Input9 - RANDOM IS ONE (exception occurred)
Input10 - Pass  # execution continued for next input check

我找到了链接,该链接与我的要求相似。区别在于不是检查文件读取错误,而是将错误堆积(如果找到)。在我的情况下,它正在检查输入。

I found link, which looks similar to my requirement. Difference is instead of checking error in file reading and stack up the error if found. In my case it is checking for inputs.

类似要求

预先感谢!

推荐答案

您定义的是一个逻辑矛盾:您想引发异常并继续正常执行。第4代语言中的引发异常的常见含义表示您想要继续正常执行。

What you've defined is a logical contradiction: you want to raise an exception and continue normal execution. The common meaning of raise exception in a 4th-generation language means that you do not want to continue normal execution. Make up your mind.

欢迎您打印一条消息,引发异常,然后继续进行正常操作。如果要稍后再引发异常,欢迎这样做。

You are welcome to print a message, not raise an exception, and continue normal operation. If you want to raise the exception later, you are welcome to do that.

如果要检查每个输入的错误,则无法进行错误检查本身是一个例外条件。我在这里有点猜想:您想报告所有差异,但是直到您处理完所有输入案例后才提出例外。尝试以下操作:它将错误处理拆分为一个非异常例程。如果您要用其他代码填充,我会保留很多异常处理内容。

If you want to check for an error on each input, then you cannot make the error check itself an exception condition. I'm guessing a little here: you want to report every discrepancy, but then not raise an exception until you've gone through all the input cases. Try this: it splits the error handling into a non-exception routine. I've left a lot of your exception-handling stuff intact, in case you want to fill it in with other code.

class RND_ERROR(Exception):
    def __init__(self, ErrNum, *arg, **kwargs):
        self.RND_ERR_NR = int(ErrNum)
        self.RND_ERR_MSG = ""

    def __str__(self):
        return "RND ERROR (0x%08X): %s" % (self.RND_ERR_NR,self.RND_ERR_MSG)

    def __repr__(self):
        return self.__str__()


def handle_error(ErrNum):
    RND_ERR_NR = int(ErrNum)
    RND_ERR_MSG = ""
    if RND_ERR_NR == 0x00000000:
        RND_ERR_MSG = "NO ERROR"
    elif RND_ERR_NR == 0x00000001:
        RND_ERR_MSG = "RANDOM NUMBER IS ONE"
    elif RND_ERR_NR == 0x00000002:
        RND_ERR_MSG = "RANDOM NUMBER IS TWO"
    elif RND_ERR_NR == 0x00000003:
        RND_ERR_MSG = "RANDOM NUMBER IS THREE"
    else:
        RND_ERR_MSG = "RANDOM NUMBER GREATER THAN THREE"

    print "RND ERROR (0x%08X): %s" % (RND_ERR_NR, RND_ERR_MSG)

def check_error(b):
    print "dict",b
    count = 0
    need_exception = False

    for i, error_nr in b.items():

        error_nr = error_nr % 2
        print "key:val",i, error_nr
        if error_nr ==0:
            count = count +1
            # print count
        elif error_nr > 0:
            # print error_nr
            handle_error(error_nr)
            need_exception = True

    if need_exception:
        raise RND_ERROR(49374)


def numGen(input):
    from random import randint
    result= {}
    for i in range(9):
        j = (randint(0, 4))
        result[i] = input+j
        result.update()
        # print "iteration", i, j
    check_error(result)

try:
    numGen(3)
except BaseException as e:
    print e
finally:
    print "Finished"

输出:

dict {0: 6, 1: 4, 2: 6, 3: 5, 4: 4, 5: 4, 6: 5, 7: 6, 8: 3}
key:val 0 0
key:val 1 0
key:val 2 0
key:val 3 1
RND ERROR (0x00000001): RANDOM NUMBER IS ONE
key:val 4 0
key:val 5 0
key:val 6 1
RND ERROR (0x00000001): RANDOM NUMBER IS ONE
key:val 7 0
key:val 8 1
RND ERROR (0x00000001): RANDOM NUMBER IS ONE
RND ERROR (0x0000C0DE): 
Finished

这篇关于处理多个相同类型的异常并在python中恢复执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆