Chapter 19-Exception Handling

Example-divzero.cpp, Page no-770

In [1]:
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
Enter Number 1: 10
 Enter Number 2: 0
 trying division operation... failed
Exception: Divide-By-Zero

Example-arrbound.cpp, Page no-772

In [1]:
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"
Maximum array size allowed = 10
Trying to refer a[1]... succeeded
Trying to refer a[15]... Out of Range in Array Reference

Example-pass.cpp, Page no-774

In [1]:
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
Maximum array size allowed = 10
Enter element to be referenced: 1
Trying to access object array 'a' for index = 1
Elemnet in Array = 1
Enter element to be referenced: 5
Trying to access object array 'a' for index = 5
Elemnet in Array = 5
Enter element to be referenced: 10
Trying to access object array 'a' for index = 10
Parent passing exception to child to handle
Child: Out of Range in Array Reference

Example-sign1.cpp, Page no-777

In [1]:
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"
Enter any number: -10
-ve Exception

Example-sign2.cpp, Page no-778

In [1]:
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)
Enter any number: 10
+ve Exception

Example-catall1.cpp, Page no-780

In [1]:
class excep2:
    pass
try:
    print "Throwing uncaught exception"
    raise excep2()
except:
    print "Caught all exceptions"
print "I am displayed"
Throwing uncaught exception
Caught all exceptions
I am displayed

Example-catall2.cpp, Page no-780

In [1]:
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"
f2() was called
f3() was called
f2() has elements with exceptions!

Example-twoexcep.cpp, Page no-782

In [1]:
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"    
Maximum array size allowed = 10
Trying to create object a1(5)... succeeded
Trying to refer a1[4]... succeeded.. a1[4] = 10
Trying to refer a1[15]... ..Array Reference Out of Range
Trying to create object a2(15)... ..Size exceeds allowable Limit

Example-uncaught.cpp, Page no-784

In [2]:
#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"
Throwing uncaught exception
---------------------------------------------------------------------------
excep2                                    Traceback (most recent call last)
<ipython-input-2-6ced6b7c0667> in <module>()
      5 try:
      6     print "Throwing uncaught exception"
----> 7     raise excep2()
      8 except excep1:
      9     print "Exception 1"

excep2: <__main__.excep2 instance at 0x00000000039A8408>

Example-myhand.cpp, Page no-786

In [1]:
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()
Throwing uncaught exception
My terminate is invoked

Example-sign3.cpp, Page no-787

In [1]:
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()"
Enter any number: 10
+ve Exception
end of main()

Example-sign4.cpp, Page no-788

In [1]:
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"
Enter any number: 0
My unexpected handler is invoked

Example-interact.cpp, Page no-790

In [1]:
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"
Maximum vector size allowed = 10
What is the size of vector you want to create: 5
Trying to create object vector v1 of size = 5 ..succeeded
Which vector element you want to access (index): 10
What is the new value for v1[ 10 ]:2
 Trying to modify a1[ 10 ]... failed
Vector reference out-of-range

Example-virtual.cpp, Page no-792

In [1]:
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
Enter Age of Father: 20
Father's Age: 20
Enter Age of Son: 45
Error: Father's Age cannot be less than son age

Example-matrix.cpp, Page no-794

In [1]:
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"
Enter Matrix A details...
How many rows? 1
How many columns? 2
Matrix[0,0] =? 1
 Matrix[0,1] =? 2
 Enter Matrix B details...
How many rows? 2
How many columns? 1
Matrix[0,0] =? 1
 Matrix[1,0] =? 2
 Matrix A is... 
1 2 
Matrix B is... 
1 
2 
Invalid matrix order for addition 
Invalid matrix order for subtraction 
E = A * B... 
5 
(Is matrix A equal to matrix B) ? No

Example-recovery.cpp, Page no-802

In [1]:
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
Sum of 7, -3, 2 computation...
Version-1 succeeds
Sum = 6
Sum of 7, 2, -3 computation...
Version-1 fails
Version-2 succeeds
Sum = 6
Sum of 3, 3, 2 computation...
Version-1 fails
Version-2 fails
Error: Overflow. All versions falied
Sum = 8

Example-new1.cpp, Page no-804

In [2]:
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
How many bytes to be allocated: 300
Memory allocation success, address = 0x3717188L

Example-new2.cpp, Page no-805

In [1]:
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)
Enter rows and columns count: 3 4
0 1 2 3 
1 2 3 4 
2 3 4 5 

Example-1, Page no-812

In [1]:
#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()
Please enter an integer value: 10.7
You enetered incorrect type of value; try again
Please enter an integer value: 8
You entered a correct type of value

Example-2, Page no-812

In [1]:
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
Press an integer between 1 - 3 to test exception handling with multiple catch blocks..3
Throwing charcter value
Caught a character value A