class number:
__num=int
def read(self):
self.__num=int(raw_input())
class DIVIDE():
pass
def div(self, num2):
if num2.__num==0:
raise self.DIVIDE()
else:
return self.__num/num2.__num
num1=number()
num2=number()
print "Enter Number 1: ",
num1.read()
print "Enter Number 2: ",
num2.read()
try:
print "trying division operation...",
result=num1.div(num2)
print "succeeded"
except number.DIVIDE:
print "failed"
print "Exception: Divide-By-Zero"
else:
print "num1/num2 =", result
ARR_SIZE=10
class array:
__arr=[int]*ARR_SIZE
class RANGE():
pass
#overloading []
def op(self, i, x):
if i<0 or i>=ARR_SIZE:
raise self.RANGE()
self.__arr[i]=x
a=array()
print "Maximum array size allowed =", ARR_SIZE
try:
print "Trying to refer a[1]...",
a.op(1, 10) #a[1]=10
print "succeeded"
print "Trying to refer a[15]...",
a.op(15, 10) #a[15]=10
print "succeeded"
except array.RANGE:
print "Out of Range in Array Reference"
ARR_SIZE=10
class array:
__arr=[int]*ARR_SIZE
class RANGE():
pass
def __init__(self):
for i in range(ARR_SIZE):
self.__arr[i]=i
#overloading []
def op(self, i, x=None):
if i<0 or i>=ARR_SIZE:
raise self.RANGE()
if isinstance(x, int):
self.__arr[i]=x
else:
return self.__arr[i]
def read(a, index):
try:
element=a.op(index)
except array.RANGE:
print "Parent passing exception to child to handle"
raise
return element
a=array()
print "Maximum array size allowed =", ARR_SIZE
while(1):
index=int(raw_input("Enter element to be referenced: "))
try:
print "Trying to access object array 'a' for index =", index
element=read(a, index)
print "Elemnet in Array =", element
except array.RANGE:
print "Child: Out of Range in Array Reference"
break
class positive:
pass
class negative:
pass
class zero:
pass
def what_sign(num): #no exception list in python and hence the except block for class zero is removed to produce the desired output
if num>0:
raise positive()
elif num<0:
raise negative()
else:
raise zero()
num=int(raw_input("Enter any number: "))
try:
what_sign(num)
except positive:
print "+ve Exception"
except negative:
print "-ve Exception"
class zero:
pass
def what_sign(num): #no exception list in python and hence the except block for class zero is removed to produce the desired output
if num>0:
print "+ve Exception"
elif num<0:
print "-ve Exception"
else:
raise zero()
num=int(raw_input("Enter any number: "))
what_sign(num)
class excep2:
pass
try:
print "Throwing uncaught exception"
raise excep2()
except:
print "Caught all exceptions"
print "I am displayed"
class ALPHA:
pass
_a=ALPHA()
def f3():
print "f3() was called"
raise _a
def f2():
try:
print "f2() was called"
f3()
except:
print "f2() has elements with exceptions!"
try:
f2()
except:
print "Need more handlers!"
print "continud after handling exceptions"
ARR_SIZE=10
class array:
__arr=[int]
__size=int
class RANGE:
pass
class SIZE:
pass
def __init__(self, SizeRequest):
self.__arr=[int]*SizeRequest
if SizeRequest<0 or SizeRequest>ARR_SIZE:
raise self.SIZE()
self.__size=SizeRequest
def __del__(self):
del self.__arr
#overloading []
def op(self, i, x=None):
if i<0 or i>=self.__size:
raise self.RANGE()
elif isinstance(x, int):
self.__arr[i]=x
else:
return self.__arr[i]
print "Maximum array size allowed =", ARR_SIZE
try:
print "Trying to create object a1(5)...",
a1=array(5)
print "succeeded"
print "Trying to refer a1[4]...",
a1.op(4, 10) #a1[4]=10
print "succeeded..",
print "a1[4] =", a1.op(4) #a1[4]
print "Trying to refer a1[15]...",
a1.op(15, 10) #a1[15]=10
print "succeeded"
except array.SIZE:
print "..Size exceeds allowable Limit"
except array.RANGE:
print "..Array Reference Out of Range"
try:
print "Trying to create object a2(15)...",
a2=array(15)
print "succeeded"
a2.op(3, 3) #a2[3]=3
except array.SIZE:
print "..Size exceeds allowable Limit"
except array.RANGE:
print "..Array Reference Out of Range"
#error because there is no block to handles exceptions of type excep2()
class excep1:
pass
class excep2:
pass
try:
print "Throwing uncaught exception"
raise excep2()
except excep1:
print "Exception 1"
print "I am not displayed"
class excep1:
pass
class excep2:
pass
def MyTerminate():
print "My terminate is invoked"
return
try:
print "Throwing uncaught exception"
raise excep2()
except excep1:
print "Exception 1"
print "I am not displayed"
except:
MyTerminate()
class zero:
pass
def what_sign(num):#no exception list in python and hence the except block is removed to produce the desired output
if num>0:
print "+ve Exception"
elif num<0:
print "-ve Exception"
else:
raise zero()
num=int(raw_input("Enter any number: "))
what_sign(num)
print "end of main()"
class zero:
pass
def MyUnexpected():
print "My unexpected handler is invoked"
def what_sign(num): #no exception list in python and hence the changes are made to produce the desired output
if num>0:
print "+ve Exception"
print "end of main()"
elif num<0:
print "-ve Exception"
print "end of main()"
else:
MyUnexpected()
num=int(raw_input("Enter any number: "))
try:
what_sign(num)
except:
print "catch all exceptions"
VEC_SIZE=10
class vector:
__vec=[int]
__size=int
class RANGE:
pass
class SIZE:
pass
def __init__(self, SizeRequest):
self.__vec=[int]*SizeRequest
if SizeRequest<0 or SizeRequest>VEC_SIZE:
raise self.SIZE()
self.__size=SizeRequest
def __del__(self):
del self.__vec
#overloading []
def op(self, i, x=None):
if i<0 or i>=self.__size:
raise self.RANGE()
elif isinstance(x, int):
self.__vec[i]=x
else:
return self.__vec[i]
print "Maximum vector size allowed =", VEC_SIZE
try:
size=int(raw_input("What is the size of vector you want to create: "))
print "Trying to create object vector v1 of size =", size,
v1=vector(size)
print "..succeeded"
index=int(raw_input("Which vector element you want to access (index): "))
print "What is the new value for v1[", index, "]:",
data=int(raw_input())
print "Trying to modify a1[", index, "]...",
v1.op(index, data) #v1[index]=data
print "succeeded"
print "New value of a1[", index, "] =", v1.op(index) #v1[index]
except vector.SIZE:
print "failed\nVector creation size exceeds allowable limit"
except vector.RANGE:
print "failed\nVector reference out-of-range"
class WRONG_AGE:
pass
class Father:
def __init__(self, n):
if n<0:
raise WRONG_AGE()
self.__f_age=n
def GetAge(self):
return self.__f_age
class Son(Father):
def __init__(self, n, m):
Father.__init__(self, n)
if m>=n:
raise WRONG_AGE()
self.__s_age=m
def GetAge(self):
return self.__s_age
basep=[Father]
father_age=int(raw_input("Enter Age of Father: "))
try:
basep=Father(father_age)
except WRONG_AGE:
print "Error: Father's Age is < 0"
else:
print "Father's Age:", basep.GetAge()
del basep
son_age=int(raw_input("Enter Age of Son: "))
try:
basep=Son(father_age, son_age)
except WRONG_AGE:
print "Error: Father's Age cannot be less than son age"
else:
print "Father's Age:", basep.GetAge()
del basep
TRUE=1
FALSE=0
class MatError:
pass
class matrix:
__MaxRow=int
__MaxCol=int
def __init__(self, row=0, col=0):
self.__MaxRow=row
self.__MaxCol=col
self.__MatPtr=[[float]*5]*5
def __add__(self, b):
c=matrix(self.__MaxRow, self.__MaxCol)
if self.__MaxRow != b._matrix__MaxRow or self.__MaxCol != b._matrix__MaxCol:
raise MatError()
for i in range(self.__MaxRow):
for j in range(self.__MaxCol):
c._matrix__MatPtr[i][j]=self.__MatPtr[i][j]+b._matrix__MatPtr[i][j]
return c
def __sub__(self, b):
c=matrix(self.__MaxRow, self.__MaxCol)
if self.__MaxRow != b._matrix__MaxRow or self.__MaxCol != b._matrix__MaxCol:
raise MatError()
for i in range(self.__MaxRow):
for j in range(self.__MaxCol):
c._matrix__MatPtr[i][j]=self.__MatPtr[i][j]-b._matrix__MatPtr[i][j]
return c
def __mul__(self, b):
c=matrix(self.__MaxRow, b._matrix__MaxCol)
if self.__MaxCol!=b._matrix__MaxRow:
raise MatError()
for i in range(c._matrix__MaxRow):
for j in range(c._matrix__MaxCol):
c._matrix__MatPtr[i][j]=0
for k in range(self.__MaxCol):
c._matrix__MatPtr[i][j]+=self.__MatPtr[i][k]*b._matrix__MatPtr[k][j]
return c
def __eq__(self, b):
if self.__MaxRow != b._matrix__MaxRow or self.__MaxCol != b._matrix__MaxCol:
return FALSE
for i in range(self.__MaxRow):
for j in range(self.__MaxCol):
if self.__MatPtr[i][j]!=b._matrix__MatPtr[i][j]:
return FALSE
return TRUE
def __assign__(self, b):
self.__MaxRow = b._matrix__MaxRow
self.__MaxCol = b._matrix__MaxCol
for i in range(self.__MaxRow):
for j in range(self.__MaxCol):
self.__MatPtr[i][j]=b._matrix__MatPtr[i][j]
def Input(self):
self.__MaxRow=int(raw_input("How many rows? "))
self.__MaxCol=int(raw_input("How many columns? "))
self.__MatPtr = []
for i in range(0,self.__MaxRow):
self.__MatPtr.append([])
for j in range(0,self.__MaxCol):
print "Matrix[%d,%d] =? " %(i, j),
self.__MatPtr[i].append(float(raw_input()))
def output(self):
for i in range(self.__MaxRow):
print ""
for j in range(self.__MaxCol):
print "%g" %self.__MatPtr[i][j],
a=matrix()
b=matrix()
print "Enter Matrix A details..."
a.Input()
print "Enter Matrix B details..."
b.Input()
print "Matrix A is...",
a.output()
print "\nMatrix B is...",
b.output()
c=matrix()
try:
c=a+b
print "\nC = A + B...",
c.output()
except MatError:
print "\nInvalid matrix order for addition",
d=matrix()
try:
d=a-b
print "\nD = A - B...",
d.output()
except MatError:
print "\nInvalid matrix order for subtraction",
e=matrix(3, 3)
try:
e=a*b
print "\nE = A * B...",
e.output()
except MatError:
print "\nInvalid matrix order for multiplication",
print "\n(Is matrix A equal to matrix B) ?",
if a==b:
print "Yes"
else:
print "No"
MAX_SIG_INT=7
MAX_UNSIG_INT=15
class OVERFLOW:
pass
def sum(i, j, k):
try:
#Version1 procedure
result=i+j
if result>MAX_SIG_INT:
raise OVERFLOW()
result=result+k
if result>MAX_SIG_INT:
raise OVERFLOW()
print "Version-1 succeeds"
except OVERFLOW:
print "Version-1 fails"
try:
#Version2 procedure
result=i+k
if result>MAX_SIG_INT:
raise OVERFLOW()
result=result+j
if result>MAX_SIG_INT:
raise OVERFLOW()
print "Version-2 succeeds"
except OVERFLOW:
print "Version-2 fails"
try:
#Version3 procedure
result=j+k
if result>MAX_SIG_INT:
raise OVERFLOW()
result=result+i
if result>MAX_SIG_INT:
raise OVERFLOW()
print "Version-3 succeeds"
except OVERFLOW:
print "Error: Overflow. All versions falied"
return result
print "Sum of 7, -3, 2 computation..."
result=sum(7, -3, 2)
print "Sum =", result
print "Sum of 7, 2, -3 computation..."
result=sum(7,2, -3)
print "Sum =", result
print "Sum of 3, 3, 2 computation..."
result=sum(3, 3, 2)
print "Sum =", result
size=int(raw_input("How many bytes to be allocated: "))
try:
data=[int]*size
print "Memory allocation success, address =", hex(id(data))
except:
print "Could not allocate. Bye..."
del data
def display(data, m, n):
for i in range(m):
for j in range(n):
print data[i][j],
print ""
def de_allocate(data, m):
for i in range(m-1):
del data[i]
m, n=[int(x) for x in raw_input("Enter rows and columns count: ").split()]
try:
data = []
for i in range(m):
data.append([])
for j in range(n):
data[i].append(0)
except:
print "Could not allocate. Bye..."
else:
for i in range(m):
for j in range(n):
data[i][j]=i+j
display(data, m, n)
de_allocate(data, m)
#ther is no goto in python
def main():
num=int(raw_input("Please enter an integer value: "))
if isinstance(num, int):
print "You entered a correct type of value"
else:
raise num
try:
main()
except:
print "You enetered incorrect type of value; try again"
main()
class Int:
def __init__(self, val):
self.value=val
class Double:
def __init__(self, val):
self.value=val
class Str:
def __init__(self, val):
self.value=val
i=int(raw_input("Press an integer between 1 - 3 to test exception handling with multiple catch blocks.."))
try:
if i==1:
print "Throwing integer value"
raise Int(1)
if i==2:
print "Throwing double value"
raise Double(1.12)
if i==3:
print "Throwing charcter value"
raise Str('A')
except Int as e: #type of an exception raised is not correctly determined in the exception block and hence use of classes
print "Caught an integer value", e.value
except Double as e:
print "Caught a double value", e.value
except Str as e:
print "Caught a character value", e.value