Add Error Handling
00:12 Pressing Ctrl + C is a common way to get out of a command-line application, right? So currently we’re in here, and now if I use the input to press Ctrl + C, it kicks me out of the game and puts me back into the command line.
Now I want to introduce some error handling into this code that prevents Python from raising this
KeyboardInterrupt error that it raises when the user presses Ctrl and C. So instead of raising it, I’m going to catch it and then do something else instead.
So I’m going to say
try and then indent the call to
input(). And if everything is fine, then I’m happy. But if instead of collecting the user input, Python’s going to raise a
KeyboardInterrupt error, then I’m going to catch it. So I’m going to say
And then in this case, I want to bring it also back to the beginning, just like we did before. I’m going to say
continue and bring the user back to the beginning of the
while loop where it’s going to print out the health and then give them another chance to input attack, heal or run away. Let’s try it out.
F5. And now when I press Ctrl + C, you see that the
KeyboardInterrupt error gets caught. And instead of quitting the program, I get a message that says
You can't quite the game by pressing Ctrl+C. If you really want to leave,
you'll need to run. Okay, found a typo here. You can’t quit.
Become a Member to join the conversation.