Python 菜单处理的嵌套异常?

Python 菜单处理的嵌套异常?,python,exception,nested,Python,Exception,Nested,我成功地用python构建了一个漂亮的菜单,但有一些例外: class InputError(Exception): pass class DigitalIoTest(Exception): pass class MotorEnableTest(Exception): pass while True: print("[1] Digital I/O Test") print("[2] Motor Enable Test")

我成功地用python构建了一个漂亮的菜单,但有一些例外:

class InputError(Exception): pass
class DigitalIoTest(Exception): pass
class MotorEnableTest(Exception): pass

while True:
        print("[1] Digital I/O Test")
        print("[2] Motor Enable Test")
        key = input("Please select test:")

        try: 
            if key == '1': raise DigitalIoTest
            elif key == '2': raise MotorEnableTest
            else: raise InputError

        except InputError:
            print("Input error!")

        except DigitalIoTest:
            pass
    
        except MotorEnableTest:
            pass
现在我需要添加另一个菜单项[3],它执行菜单中的所有测试。这就是我迄今为止所尝试的:

class InputError(Exception): pass
class DigitalIoTest(Exception): pass
class MotorEnableTest(Exception): pass
class AllTests: pass

while True:
        print("[1] Digital I/O Test")
        print("[2] Motor Enable Test")
        print("[3] All Tests")
        key = input("Please select test:")

        try: 
            if key == '1': raise DigitalIoTest
            elif key == '2': raise MotorEnableTest
            elif key == '3': raise AllTests
            else: raise InputError

        except InputError:
            print("Input error!")

        except DigitalIoTest:
            pass
    
        except MotorEnableTest:
            pass

        except AllTests:
            try:  
                raise DigitalIoTest
                raise MotorEnableTest
            except: 
                pass

这不符合预期。有人能给我一个提示吗?我如何实现这样一个嵌套的异常来连续执行所有的测试?

您使用异常来指示程序的正常流应该做什么,这实际上不是异常的用途。这样写怎么样:

while True:
        print("[1] Digital I/O Test")
        print("[2] Motor Enable Test")
        print("[3] All Tests")
        key = input("Please select test:")

        
        if key == '1': 
            do_what_you_need_for_1()
        elif key == '2': 
            do_what_you_need_for_2()
        elif key == '3': 
            do_what_you_need_for_3()
        else: raise InputError


如果需要调用多个函数,请调用多个函数。为异常(如输入错误)保留异常。

等等,什么?为什么要使用异常呢?因为我不知道如何用另一种如此简单和优雅的方式来实现这一点(我指的是少量代码和良好的结构)。但是。。。即使忽略异常的预期用途,这也是一个额外的尝试层,除了围绕一个可以自己处理所有事情的elif链进行处理之外。这比没有将异常引入到图片中要复杂得多。谢谢,那会有用的。但是,如果我仍然喜欢“例外”方式,有没有解决办法呢?我错过了旧编程时代的“goto-label”指令:-)@StefanWyss goto的使用早就被认为是有问题的,有理由避免在正常流中使用异常。Python尤其强调可读性。这可能是一个很好的机会,根据语言的原则编写代码——除其他外,其他人会发现你的代码更可读,不会让人困惑。你说服了我。我将使用功能菜单方法。谢谢