Back

Dealing with multiple errors

A try block in Python can look for many different errors.

Q1. Get this code working in Python.

1    import sys
2    # Handling lots of different kinds of errors
3    try:
4        myFile = open("Data.txt","r")
5        newPoem = myFile.writePoem("This is not a poem.")
6        number = int('name')
7        value = 101/0
8    except IOError:
9        print ("Error related to I/O.")
10  except ValueError:
11     print ("Cannot convert the data to data type integer.")
12  except ZeroDivisionError:
13     print ("You cannot divide by zero.")
14  except:
15     print ("Error:", sys.exc_info()[0])

Q2. Describe how the code works.
Q3. Look at lines 4 and 5. Why is there an I/O problem?
Q4. Comment out lines 4 and 5. What error do you get now?
Q5. Explain the error you got in Q4.
Q6. Comment out line 6. What error do you get now?
Q7. Explain your answer to Q6 above.
Q8. What does line 15 do?
Q9. Why do you need line 1?
Q10. Add another exception to the code and try and force that error to happen.

Back