replit

Before you start this course, you must login to Replit

If you have forgotten your Replit account user name or password, ask your Coder Coach.

CoderSports


13.4-Basic-Exceptions—Make

Instructions

In the make tasks, students use the skills learned in the earlier stages of PRIMM to create their own program based on a description of what it should do.

Make sure that the students add comments to explain what the code does.


Learning Objectives/Goals

Concept Explanation Code
Attempt the code Attempt to run the code. try
Catch errors Only run the code if the try code from before creates an exception. except
Run if no errors Runs the code only if there is no error else
Always run Runs the code regardless of whether there is an error finally

Here is an example of the syntax.

# Tries to run the following code.
try:
    print(name)
# If there is a `NameError`, run this code
except NameError:
    print("The variable has not been assigned")
# If there is a `ValueError`, run this code
except ValueError:
    print("You entered a non integer input")
# If there is any other type of error, run this code
except:
	print("Something else went wrong")
# If there is no error, run this code
else:
	print("Nothing went wrong")
# Run this code regardless of whether there was an error. 
finally:
	print("The try except has finished")

In this unit you will learn about

When a program runs and encounters an error, Python will generate an exception and crash. Exception handling allows us to work with these exceptions to help prevent crashes.

There are lots of built in Python exceptions. These exercises will focus on exceptions to handle undefined variables and input of the wrong data type.

Exception handling uses very similar syntax to if…else statements, just with the key commands try and except.

Help!! My code doesen’t work!

  • Indentation logic – accidentally nesting statements that shouldn’t be nested
  • Not specifying the type of error in the branches before a plain, except, else or finally

Hints