Python 自定义异常类应该允许在引发后继续执行程序

标签 python exception python-2.7

我写了一个 Python 程序,它有一个名为 TAException 的自定义异常类,它运行良好。 但是一个新的要求迫使我扩展它的功能。如果用户在 程序启动 如果引发 TAException,程序不应停止执行。

下面你会看到我是如何尝试实现它的。在 main() 中,如果已设置该标志,则会调用 TAException.setNoAbort() 。其余的可能是不言自明的。 重点是:显然是行不通的。当引发 TAException 时,程序总是中止。 我知道为什么它不起作用,但我不知道如何以不同的方式实现它。你能告诉我一个优雅的方法来做到这一点吗?

class TAException(Exception):
    _numOfException = 0                                                 # How often has this exception been raised?
    _noAbort = False                                                    # By default we abort the test run if this exception has been raised.

    def __init__(self, TR_Inst, expr, msg):
        '''
        Parameters:
            TR_Inst:    Testreport instance
            expr:       Expression in which the error occured.
            msg:        Explanation for the error.
        '''
        if TR_Inst != None:
            if TAException._noAbort is True:                            # If we abort the test run on the first exception being raised.
                TAException._numOfException += 1                        # Or else only count the exception and continue the test run.
                                                                        # The status of the testreport will be set to "Failed" by TestReportgen.
            else:
                TR_Inst.genreport([expr, msg], False)                   # Generate testreport and exit.

    @staticmethod
    def setNoAbort():
        '''
        Sets TAException._noAbort to True.
        '''
        TAException._noAbort = True

最佳答案

当使用参数 -n 时,您的程序不应引发异常,而应使用警告(不会停止您的程序)。您可以在此处找到有关警告的更多信息:http://docs.python.org/2/library/warnings.html#module-warnings

关于Python 自定义异常类应该允许在引发后继续执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14892543/

相关文章:

python - 具有工作时间上下文的日期时间列表,计算非工作时间

python - 我在哪里可以从 Firefox 获取有关 :support 的原始信息

python - 根据阈值将 NumPy 数组转换为 0 或 1

jakarta-ee - JAVA EE - EJB/CDI/JPA : Exception Handling

python - 如何在 ReportLab 中将酒吧聊天中的每个单独的酒吧设置为不同的颜色?

Python - 找不到 get-pip.py

python - 使用关联列表对象的函数迭代列表

python - 精确的计算和绘图

mysql - 如何让 MySQL 在 SQL 中抛出条件运行时异常

java - ArrayList 迭代给出异常 java.util.ConcurrentModificationException