Exceptions can be used to indicate problems that occur when an object is being con- structed. Write a Python program that shows a constructor passing information about constructor fail- ure to an exception handler that occurs after a try statement. The exception raised also should contain the arguments sent to the constructor.

What will be an ideal response?

```
# Raising exceptions in constructors.

class MonthError( StandardError ):
"""Error with month instance"""
pass

class Month:
"""Represent month as a string"""

months = { 1 : "January",
2 : "February",
3 : "March",
4 : "April",
5 : "May",
6 : "June",
7 : "July",
8 : "August",
9 : "September",
10 : "October",
11 : "November",
12 : "December" }

def __init__( self, monthNumber ):
"""Month constructor; accept integer argument"""

# attempt to assign value to monthString instance
try:
self.monthString = self.months[ monthNumber ]
except KeyError:
raise MonthError, \
"Invalid month value (%d)--see Month.months" \
% monthNumber

def __str__( self ):
"""String representation of Month"""

return self.monthString

# main program

# continually prompt user until they enter integer value
# in range [1, 12]
while 1:

# get integer value from user
try:
userInteger = int(
raw_input( "\nEnter integer for month: " ) )
monthName = str( Month( userInteger ) )
break

# if user did not enter integer
except ValueError:
print "Must enter integer value!"

# if integer not in range [1, 12]
except MonthError, exception:
print exception

print "The month name is", monthName
```
Enter integer for month: 0
Invalid month value (0)--see Month.months
Enter integer for month: a
Must enter integer value!
Enter integer for month: 12
The month name is December

Computer Science & Information Technology

You might also like to view...

________ graphics are created using geometrical formulas and can be easily edited and layered

Fill in the blank(s) with correct word

Computer Science & Information Technology

A technician is asked to re-terminate a wall jack that has become loose. Upon looking at the wiring, the technician notices that it was originally wired as 568A. The company implemented a policy stating that all cable terminations should adhere to the 568B standard. With this in mind the technician should:

A. re-terminate both ends of the cable to the 568B standard. B. run a new cable and terminate both ends to the 568B standard. C. reterminate the nonloose end of the cable to the 568B standard. D. reterminate the loose end of the cable to the 568B standard

Computer Science & Information Technology