12. Error Handling

General Exception

When an error occurs in Python you may see a chunk of red text like this:

errror1

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:

error2

If we enter a correct value then the program will execute normally:

error3

But if an error occurs (such as writing a string when an integer is expected) then the exception code will run:

error4

You can add the else command to your code that will execute only if there are no errors:

error5

If a valid number is entered then the else code will be printed:

error6

If a code generating an error is entered then the except code will be printed:

error7


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:

error8

If a value error occurs, such as when the wrong data type is entered, then related code will be printed:

error9Or if the user tries to divide by zero then a Zero Division Error will be triggered which prints a relevant response:

error10

Other types of exception can be found here.


Practice Tasks

  1. Create a program that, in the try section, asks a userĀ for their name and then prints it twice. Spell print incorrectly.
  2. Create a general Exception that prints a message to double check your code. Check it works.
  3. Fix the misspelled print and add an else line that prints Goodbye! Check it works.
  4. Change the general Exception to a NameError and test the program with print spelled correctly and then incorrectly.