2️⃣

19.2 Try/Except

Try/Except

Similar to if/else, try/except has a first statement, try, and a second statement, except. However, using try/except allows you to deal with errors without crashing your program.
try is the keyword that allows you to test a block of code for errors. All you need to do is type try: and remember to indent the next line of code
except is the keyword that allows you to run a certain set of code if an error was raised in the try part. All you need to do is type except:, although there is more that you could add before the colon. We will get into that later.
try: x = 1 y = "hi" x + y #this causes the error except: print("uh oh, something went wrong")
In this example, the except will run because an error was thrown when adding an integer, x, with a string, y. However, x and y will still exist because, when using try/except, all the lines of code before the error will run (try stops running code at the first error, then goes to the except). This means that I could still access x and y if I needed to.

Practice

Integer Checker

Create a program that asks the user to input an integer. Try to convert that into an integer. If it doesn’t work, send the user a message telling them to input an actual integer next time.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.