The purpose of today's lab is to practice using exceptions and exception handling mechanisms within Python. The lab has two components:

  1. An exploration of the built-in exception types of Python
  2. A model of the solar system

Create a lab10 folder, like normal.

Exploring Exceptions

Do this...

In your lab10 folder create a new python file called exercise1.py.

Now that we have a file to work in, let's see what kinds of exceptions are generated for us automatically.

Exercise 10.1

Each of the following expressions raises an exception. Copy each expression into your file (one at a time), run the file to see the error that is raised, and then put the expression in a try/except block that deals with the specific form of exception raised. For example, if the expression was

import happiness
this would generate an ImportError (unless you somehow defined a happiness module), so the resulting code would be:
try:
    import happiness
except ImportError as ie:
    print('dealt with ImportError:', ie)

The expressions:

  1. 'hi' + 4
  2. 10 / 0
  3. 'person'.find_first('e')
  4. [0,1,2]['summer']
  5. ['hi','there','student'][5]
  6. print(name)
  7. 9 <= (3, 4)
  8. f = open('missingFile.txt')

A Model of the Solar System

As we have seen, modeling real-world objects is one of the motivations for object-oriented programming. It is also an ideal scenario to practice exception handling, as we can effectively use exceptions to maintain class invariants, instead of the more heavy-handed approach of crashing the program any time something undesirable occurs.

Do this...

Begin by copying each of the following 3 files into your lab10 folder. You can easily do this by right-clicking on the link and choosing Save link as...

Take a moment to familiarize yourself with the code in each file before continuing.

Each of the starting code files implements a class. While functional, there is no error checking, which means any solar system we might model could end up being far from realistic. Let's work on remedying this issue.

Exercise 10.2

Add code to the Planet class to maintain the invariant that the radius, mass and distance of a planet from the sun must be positive numbers. If the value provided by the calling program does not meet the invariant, raise an appropriate exception (e.g., ValueError('Planet numeric properties must be positive') )

Now, add testing code at the bottom of the file (that will not be run if the file is imported) to verify that you can correctly construct valid planets, and that an exception is raised if you attempt to construct an invalid planet.

Note: You do not need to add tests for the other methods in the class, but you should create at least two valid planets without raising an exception, and you should check that creating 3 planets that are invalid for different reasons each raise an exception.

Practice makes perfect, so....

Exercise 10.3

Repeat exercise 10.2, but now for the Sun class. Again, the radius and mass should be positive numbers, but now the temperature should also be greater than absolute zero (-273.15°C).

Also add appropriate tests in this file that will not be run when the module is imported.

Our solar system doesn't have numeric properties we need to check, but here we would really like to know that we are making a system with a sun and planets, not a grouping of something else. Python generally avoids checking the types of variables, choosing instead to assume that the object will be good until proven otherwise. However, for our purposes today, let's make sure that when we add a sun, it is actually a Sun, and similarly for planets.

Exercise 10.4

To check that an object is actually the type we are looking for, we can use the function isinstance(). This function has two arguments: the object and the class. Replace the body of the add_sun method with the following:

if isinstance(a_sun, Sun):
    self._sun = a_sun
else:
    raise TypeError('add_sun(): cannot add ' + str(type(a_sun)) + ' to solar system')
Similarly, add code to the add_planet() method to verify that the given parameters are an appropriate type, raising a TypeError with a helpful message if they are not. As in previous exercises, add some testing code to your file.

Visualize the Solar System

Modeling a solar system is all well and good, but a visual representation would be even better. We can use turtle graphics to get a better feel of what is happening.

Exercise 10.5

Create a new file in your lab10 package called driver.py. This will start as an empty file, and will become the place that we bring together the graphical components of our task.

The job of the driver is to set up our output window and get everything set up in our solar system. Copy and paste the following code into driver.py :

import turtle
from solar_system import *

window = turtle.Screen()
window.setworldcoordinates(-1, -1, 1, 1)

ss = Solar_System()
ss.add_sun(Sun("SUN", 8.5, 1000, 5800))
ss.add_planet(Planet("EARTH", .475, 5000, 0.6, 'blue'))

# Keep the window open until it is clicked
window.exitonclick()
			

Take a minute to understand/guess what this code is doing (i.e., add some comments once you figure out a piece to remind yourself what is happening).

As written, this code will not run because it assumes updates to our classes to support graphics that we have not yet made. Add the following changes to get things running appropriately:

With each of these changes made, you should be able to run your driver program and see a nice visualization of your solar system. Note: don't get too excited. Planets don't actually move... :-(

As a last step, let's allow the user to add another planet of their choosing.

Exercise 10.6

Add code that prompts the user for each of the following:

Using the entered values, create a new planet and add it to the solar system. Your code should never crash (that is, be ready for any possible exception). Further, verify that the new planet appears in the visualization appropriately.

For example, entering Mars, distance: 0.51; mass: 3000; radius: 0.2; color: red, produces a reasonable approximation of the planet mars.

Before submitting your code, double check that all files have appropriate documentation and that all of your files are saved in their final state (there should be no asterisks next to the name of the file in thonny).

Checking In

Submit all the code and supporting files for the exercises in this lab. We will grade this exercise according to the following criteria:

If you’re working on a lab computer, don’t forget to log off of your machine when you are finished!