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
You might also like to view...
Answer the following statements true (T) or false (F)
1. The statement c = d; checks to see if variables c and d have the same value 2. If x is a type double variable and n is of type int, the following assignment statements are equivalent. x = n; x = (double)n; 3. If the value of x is 735, the statement printf("%4d", x); will display four blanks followed by 735. 4. The value of the expression x + y * z * z is always the same as the value of x + ((y * z) * z) 5. A type char literal is enclosed in single quotes.
When you give a presentation with hidden slides, you have the option of revealing the hidden slides while displaying the presentation
Indicate whether the statement is true or false
Two pictures with text wrapping assigned as square can be placed on top of one another, as the text wrapping option only applies to text's interaction with graphics (and not graphics with graphics)
Indicate whether the statement is true or false
In atmospheric perspective, as items recede on the picture plane, they __________.
a. loose detail b. loose texture c. loose saturation d. all of the above