Chapter 17: Exception Handling

Example 17.1, Page Number: 397

In [1]:
print "start"

try:                                          #start a try block
    print "Inside try block"
    raise Exception(99)                       #raise an error
    print "This will not execute"
except Exception,i:                           #catch an error
    print "Caught an exception -- value is:",
    print i

print "end"
start
Inside try block
Caught an exception -- value is: 99
end

Example 17.2, Page Number: 399

In [1]:
import sys



def main():
    print "start"
    try:                                          #start a try block
        print "Inside try block"
        raise Exception(99)                       #raise an error
        print "This will not execute"
    except Exception,i:                           #catch an error
        if isinstance(i,float):
            print "Caught an exception -- value is:",
            print i
        else:
            print "Abnormal program termination"
            return
    print "end"

    
main()
start
Inside try block
Abnormal program termination

Example 17.3, Page Number: 400

In [2]:
def Xtest(test):
    print "Inside Xtest, test is: ",test
    if(test):
        raise Exception(test)
        
print "start"

try:                         #start a try block
    print "Inside try block"
    Xtest(0)
    Xtest(1)
    Xtest(2)
except Exception,i:          #catch an error
    print "Caught an exception -- value is:",
    print i

print "end"
start
Inside try block
Inside Xtest, test is:  0
Inside Xtest, test is:  1
Caught an exception -- value is: 1
end

Example 17.4, Page Number: 401

In [3]:
def Xhandler(test):
    try:
        if(test):
            raise Exception(test)
    except Exception,i:
        print "Caught One! Ex #:",i
        
print "start"

Xhandler(1)
Xhandler(2)
Xhandler(0)
Xhandler(3)

print "end"
start
Caught One! Ex #: 1
Caught One! Ex #: 2
Caught One! Ex #: 3
end

Example 17.5, Page Number: 401

In [4]:
class MyException:
    def __init__(self,s):
        self.str_what=s
        
#Variable declaration
a=None 
b=None

try:
    print "Enter numerator and denominator:"
    #User-input
    a=10                                     
    b=0
    if not(b):
        raise MyException("Cannot divide by zero!")
    else:
        print "Quotient is",a/b
except MyException as e:        #catch an error
    print e.str_what
    
Enter numerator and denominator:
Cannot divide by zero!

Example 17.6, Page Number: 403

In [5]:
class MyException:
    def __init__(self,s):
        self.x=s
        
def Xhandler(test):
    try:
        if(test):
            raise MyException(test)
        else:
            raise MyException("Value is zero")
    except MyException as i:
        if isinstance(i.x,int):
            print "Caught One! Ex #:",i.x
        else:
            print "Caught a string:",
            print i.x
        
print "start"

Xhandler(1)
Xhandler(2)
Xhandler(0)
Xhandler(3)

print "end"
start
Caught One! Ex #: 1
Caught One! Ex #: 2
Caught a string: Value is zero
Caught One! Ex #: 3
end

Example 17.7, Page Number: 404

In [6]:
class B:
    pass

class D(B):
    pass

derived=D()

try:
    raise B()
except B as b:
    print "Caught a base class."
except D as d:
    print "This wont execute."
    
Caught a base class.

Example 17.8, Page Number: 405

In [7]:
def Xhandler(test):
    try:
        if test==0:
            raise Exception(test)       #throw int
        if test==1:
            raise Exception('a')        #throw char
        if test==2:
            raise Exception(123.23)     #throw double
    except:                             #Catches all exceptions
        print "Caught One!"

print "start"

Xhandler(0)
Xhandler(1)
Xhandler(2)

print "end"
start
Caught One!
Caught One!
Caught One!
end

Example 17.9, Page Number: 405

In [8]:
class MyException:
    def __init__(self,s):
        self.x=s
        
def Xhandler(test):
    try:
        if test==0:
            raise MyException(test)       #throw int
        if test==1:
            raise MyException('a')        #throw char
        if test==2:
            raise MyException(123.23)     #throw double
    except MyException as i:
        if isinstance(i.x,int):           #catch an int exception
            print "Caught",i.x              
        else:                             #catch all other exceptions
            print "Caught One!"
        

print "start"

Xhandler(0)
Xhandler(1)
Xhandler(2)

print "end"
start
Caught 0
Caught One!
Caught One!
end

Example 17.10, Page Number: 407

In [9]:
class MyException:
    def __init__(self,s):
        self.x=s
 
#This function can only throw ints, chars and doubles
def Xhandler(test):
    if test==0:
        raise MyException(test)       #throw int
    if test==1:
        raise MyException('a')        #throw char
    if test==2:
        raise MyException(123.23)     #throw double
     

print "start"
try:
    Xhandler(0)
except MyException as i:
    if isinstance(i.x,int):           #catch an int exception
        print "Caught int"                  
    elif isinstance(i.x,str):        #catch a char exception
        print "Caught char"
    elif isinstance(i.x,float):       #catch a float exception
        print "Caught double"

print "end"
start
Caught int
end

Example 17.11, Page Number: 408

In [10]:
def Xhandler():
    try:
        raise Exception("hello")  #throw a char *
    except Exception,c:           #catch a char *
        print "Caugh char * inside Xhandler"
        raise                     #rethrow char * out of function
        
print "start"
try:
    Xhandler()
except Exception,c:
    print "Caught char * inside main"
    
print "end"
start
Caugh char * inside Xhandler
Caught char * inside main
end

Example 17.12, Page Number: 410

In [12]:
from ctypes import *

#Variable declaration
p=[]

try:
    for i in range(32):
        p.append(c_int())
except MemoryError,m:
    print "Allocation failure."
        
for i in range(32):
    p[i]=i
    
for i in range(32):
    print p[i],
    
    
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Example 17.13, Page Number: 410

In [13]:
from ctypes import *

#Variable declaration
p=[]


for i in range(32):
    p.append(c_int())    
if not(p):
    print "Allocation failure."
        
for i in range(32):
    p[i]=i
    
for i in range(32):
    print p[i],
    
    
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Example 17.13, Page Number: 412

In [14]:
class three_d:
    def __init__(self,i=0,j=0,k=0):    #3=D coordinates
        if(i==0 and j==0 and k==0):
            self.x=self.y=self.z=0
            print "Constructing 0, 0, 0"
        else:
            self.x=i
            self.y=j
            self.z=k
            print "Constructing",i,",",j,",",k
    def __del__(self):
        print "Destructing"
    #new overloaded relative to three_d.
    def __new__(typ, *args, **kwargs):
        obj = object.__new__(typ, *args, **kwargs)
        return obj
    def show(self):
        print self.x,",",
        print self.y,",",
        print self.z
    
p1=[]*3
p2=[]
        
try:
    print "Allocating array of three_d objects."
    for i in range(3):                           #allocate array
        p1.append(three_d())
    print "Allocating three_d object."
    p2.append(three_d(5,6,7))                    #allocate object
except MemoryError:
    print "Allocation error"
    
p1[2].show()
p2[0].show()


for i in xrange(2,-1,-1):
    del p1[i]                                     #delete array
print "Deleting array of thee_d objects."

del p2[0]                                         #delete object
print "Deleting three_d object."
Allocating array of three_d objects.
Constructing 0, 0, 0
Constructing 0, 0, 0
Constructing 0, 0, 0
Allocating three_d object.
Constructing 5 , 6 , 7
0 , 0 , 0
5 , 6 , 7
Destructing
Destructing
Destructing
Deleting array of thee_d objects.
Destructing
Deleting three_d object.
In [ ]: