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.
tryis 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
exceptis the keyword that allows you to run a certain set of code if an error was raised in the
trypart. 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,
ywill 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
yif I needed to.
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.