Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Add Error Handling

00:00 Let’s get started on those stretch goals. The first one is to prevent the player from exiting the game by pressing Ctrl + C. Let’s try that out first before we start tackling it.

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.

00:30 This is a common way to exit command lines if you’re kind of stuck somewhere, and you just want to quit it fast. But for this game, we want the player to explicitly run away.

00:40 And we just before handled any sort of other keyboard input that the player could do by pressing different characters than A, H, and R.

00:50 But now they still have a way to do something unexpected when they have a chance to input something, right? And in this case, that’s quitting the game using Ctrl + C instead of running away.

01:02 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.

01:21 Let’s try this out. What I want to wrap here is the input() action by the user. This is where they use the keyboard, and this is where I can catch the error.

01:31 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 except KeyboardInterrupt.

01:53 Then I want to print a message:

01:58 "You can't quit the game by pressing Ctrl+C." And then maybe tell them what else they can do if they really want to quit. "If you really want to leave, you'll need to (R)un."

02:24 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.

02:46 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.

03:09 But the functionality is how I expected. And we introduced a little bit of error handling in the code as well. Good job. First stretch goal done. Let’s move on to the next one.

Become a Member to join the conversation.