Chapter 13: Managing Errors & Exceptions

example 13.1, page no. 231

In [2]:
"""
there is no need of semicolon. We will show error for something else
"""

print "Hello Python..."
Hello Python...

example 13.2, page no. 232

In [5]:
a = 10
b = 5
c = 5
x = a/(b-c) #It will show ZeroDivisionError
print "x = ", x
y = a/(b+c)
print "y = ", y
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-5-9289236a4a07> in <module>()
      3 b = 5
      4 c = 5
----> 5 x = a/(b-c)
      6 print "x = ", x
      7 y = a/(b+c)

ZeroDivisionError: division by zero

Example 13.3 page no : 235

In [2]:
a = 10
b = 5
c = 5
try:
    x = a/(b-c)
except Exception,e :
    print "Division by zero"
y = a/(b+c)
print "y = ",y
Division by zero
y =  1

Example 13.4 page no : 236

In [4]:
import sys
invalid = 0
count = 0
for i in sys.argv:
    try:
        a = int(i)
    except:
        invalid += 1
        print "Invalid number" , i
        continue
    count += 1

print "Valid Numbers : " ,count
print "Invalid numbers ",invalid
        
 Invalid number -c
Invalid number -f
Invalid number /tmp/tmp1tOqar/profile_default/security/kernel-082ebfe6-5650-4ba4-8bcf-cd17bc99af7a.json
Invalid number --IPKernelApp.parent_appname='ipython-notebook'
Invalid number --profile-dir
Invalid number /tmp/tmp1tOqar/profile_default
Invalid number --parent=1
Valid Numbers :  0
Invalid numbers  7

example 13.5, page no. 239

In [6]:
a = [5,10]
b = 5
try:
    x = a[2]/b - a[1]
except AssertionError:
    print "AssertionError:"
except IndexError:
    print "Array Index Error"
except Exception:
    print "Any Error"
y = a[1]/a[0]
print "y = " , y 
Array Index Error
y =  2

Example 13.6 page no : 239

In [8]:
x = 5
y = 1000

class MyException(Exception):
    def __init__(self, message):
        Exception.__init__(self, message)
    def error(self):
        print self.message

try:
    z = x/y
    if(z<0.01):
        raise MyException("Number is too small")
except MyException, error:
    print "Caught MyException"
    print error.message
finally:
    print "I am always here"
Caught MyException
Number is too small
I am always here