Try and Except - Lakelands Computing

Title
Go to content
Try and Except
When computer programs encounter something that isn't what they are expecting they create an error and stop the program. This is not ideal, so there is a way around it using Try and Except:

  • print (x)

This would error as the computer does not know what the variable x is, but if we wrote

try:
  • print (x)

except:
  • print ("sorry, I don't know what x is")
  • print ("can you input x for me?"
  • x = input()

Now it doesn't error but lets the user know there is a problem and asks the user for guidance.
You can use try and except for inputs, when using variables, when importing data from files (highly recommended)

You can have different except statements based on the error produced (here's a list of the standard exceptions). You can use if statements with except (see trinket).  You can also have a finally statement - this will run after the try and except. It will run if the try is succesful and it will run if the try fails and the except was carried out.
It is still possible to make code error even with a try and except - just type a letter in instead of the numbers in the example. I deliberately set it up to make this possible. A better way to do this bit of programming is below, but the point is if you want to have code that can manage exceptions you need to think about what exceptions you might get:
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content