Dealing with multiple errors - Answers
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. The code imports the sys module (required for line 15). It then tries to open a file object, write to a file object, convert a data type and divide by zero. Three exceptions have been set up to catch problems. There is also a fourth one, which catches any other problems apart from the three specific ones.
Q3. On line 4, an I/O object has been opened for reading. On line 5, we are trying to write to the I/O object.
Q4. When you comment out lines 4 and 5, you get, 'Cannot convert the data to data type integer.'
Q5. The error you got in Q4 occurs because you are trying to convert a string of letters into a number.
Q6. When you comment out line 6, you get, 'You cannot divide by zero.'
Q7. You are tring to divide a number by zero, so get an error.
Q8. Line 15 catches all other errors or problems that occur. The three specific ones in the code are tried first but if any other error occurs, a system message is generated.
Q9. You need line 1 because you are generating a system message on line 15 using functions from this module.
Q10. Various other exceptions could be chosen. Students should refer to the Python documentation for potential exceptions or look for examples on the Internet to include.