When an error occurs in Python you may see a chunk of red text like this:
This is actually very useful when creating programs as it tells us the exact line of the error (10), and its type (NameError).
However a completed program should have code in place for when an unexpected error occurs – we call this exception handling.
In the code below Python will attempt to run the code indented beneath try. If there are no errors then the code will stop at its final line (just before except). If an error does occur then the Exception code will be run:
If we enter a correct value then the program will execute normally:
But if an error occurs (such as writing a string when an integer is expected) then the exception code will run:
You can add the else command to your code that will execute only if there are no errors:
If a valid number is entered then the else code will be printed:
If a code generating an error is entered then the except code will be printed:
Specific Exception Commands
The Exception command is for any general error that occurs. You can use specific except commands for a variety of errors.
Below is a program with two different specific exception commands for one try statement:
If a value error occurs, such as when the wrong data type is entered, then related code will be printed:
Or if the user tries to divide by zero then a Zero Division Error will be triggered which prints a relevant response:
Other types of exception can be found here.
- Create a program that, in the try section, asks a user for their name and then prints it twice. Spell print incorrectly.
- Create a general Exception that prints a message to double check your code. Check it works.
- Fix the misspelled print and add an else line that prints Goodbye! Check it works.
- Change the general Exception to a NameError and test the program with print spelled correctly and then incorrectly.