Let's say I have this piece of code in 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.
I would appreciate it if someone can help me with this problem.
Thank you!
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.