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.1-Basic-Exceptions—Predict-Run

Instructions

At the ‘predict’ & ‘run’ stages students work entirely with example code. They should inspect it carefully and write a prediction about what it will do.

They then run the code and compare the result to their prediction.


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