如何以不同的方式处理两个异常(动作1和动作2),但是如果它们一起出现,则用动作1处理它们?

时间:2022-09-11 14:45:13

Let's say I have this piece of code in Python:

假设我在Python中有这段代码:

while True:
    try:
        raise CustomError

    except CustomError:
        # Action1

    except KeyboardInterrupt:
        # Action2

I want whenever CustomError happens, Action1 handles it. But if and only if I have a KeyboardInterruptError, then Action2 happens (even though CustomError is still raised). Now what happens in my code is Action1 always happens and if user press CTRL+C , the code ignores it and still Action1 occurs.

我希望每当CustomError发生时,Action1都会处理它。但是当且仅当我有一个KeyboardInterruptError时,就会发生Action2(即使仍然引发了CustomError)。现在我的代码中发生的事情是Action1总是会发生,如果用户按下CTRL + C,代码会忽略它,但仍然会发生Action1。

I would appreciate it if someone can help me with this problem.

如果有人可以帮我解决这个问题,我将不胜感激。

Thank you!

1 个解决方案

#1


0  

There's nothing you can do about the timing; if CustomError is raised before you type Control-C, then Action1 is at least going to begin. However, it looks like you want two try statements, one nested in the other:

关于时间安排你无能为力;如果在键入Control-C之前引发了CustomError,则Action1至少会开始。但是,看起来你想要两个try语句,一个嵌套在另一个中:

try:
    try:
        raise CustomError
    except CustomError:
        Action1
except KeyboardInterrupt:
    Action2

This ensures that the keyboard interrupt will be caught and handled whether it happens while control is in the inner try clause or in the CustomError handler.

这可确保在内部try子句或CustomError处理程序中控件发生时捕获和处理键盘中断。

#1


0  

There's nothing you can do about the timing; if CustomError is raised before you type Control-C, then Action1 is at least going to begin. However, it looks like you want two try statements, one nested in the other:

关于时间安排你无能为力;如果在键入Control-C之前引发了CustomError,则Action1至少会开始。但是,看起来你想要两个try语句,一个嵌套在另一个中:

try:
    try:
        raise CustomError
    except CustomError:
        Action1
except KeyboardInterrupt:
    Action2

This ensures that the keyboard interrupt will be caught and handled whether it happens while control is in the inner try clause or in the CustomError handler.

这可确保在内部try子句或CustomError处理程序中控件发生时捕获和处理键盘中断。