In [ ]:
# exceptions: error handling
# https://docs.python.org/2.7/tutorial/errors.html
# pre-production

In [1]:
# example 1:
num1 = int(raw_input("please enter the number1:"))
num2 = int(raw_input("please enter the number2:"))
result = num1/num2
print "result is {}".format(result)


please enter the number1:10
please enter the number2:2
result is 5

In [3]:
# exception 1
num1 = int(raw_input("please enter the number1:"))
num2 = int(raw_input("please enter the number2:"))
result = num1/num2
print "result is {}".format(result)


please enter the number1:ten
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-313ae63bb131> in <module>()
      1 # exception 1
----> 2 num1 = int(raw_input("please enter the number1:"))
      3 num2 = int(raw_input("please enter the number2:"))
      4 result = num1/num2
      5 print "result is {}".format(result)

ValueError: invalid literal for int() with base 10: 'ten'

In [4]:
# exception 2:
num1 = int(raw_input("please enter the number1:"))
num2 = int(raw_input("please enter the number2:"))
result = num1/num2
print "result is {}".format(result)


please enter the number1:10
please enter the number2:0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-4-3b0c3af6a024> in <module>()
      2 num1 = int(raw_input("please enter the number1:"))
      3 num2 = int(raw_input("please enter the number2:"))
----> 4 result = num1/num2
      5 print "result is {}".format(result)

ZeroDivisionError: integer division or modulo by zero

In [5]:
# what are different exceptions in python

import exceptions as e

In [6]:
print dir(e)


['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__doc__', '__name__', '__package__']

In [ ]:
# try..except..else..finally
# try -> to compute or most important task.
# except -> handling your exceptions.
# else -> if try is True.. then go to else.

In [7]:
# run1
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except:
    print "please enter numbers.Make sure your denominator is non-zero"
else:
    print "result is {}".format(result)


please enter the number1:10
please enter the number2:2
result is 5

In [8]:
# run2
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except:
    print "please enter numbers.Make sure your denominator is non-zero"
else:
    print "result is {}".format(result)


please enter the number1:ten
please enter numbers.Make sure your denominator is non-zero

In [9]:
# run3
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except:
    print "please enter numbers.Make sure your denominator is non-zero"
else:
    print "result is {}".format(result)


please enter the number1:10
please enter the number2:0
please enter numbers.Make sure your denominator is non-zero

In [10]:
# now lets tell crearly that its a value error or a zero division error.
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except (ZeroDivisionError,ValueError):
    print "please enter numbers.Make sure your denominator is non-zero"
else:
    print "result is {}".format(result)


please enter the number1:ten
please enter numbers.Make sure your denominator is non-zero

In [11]:
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except (ZeroDivisionError,ValueError):
    print "please enter numbers.Make sure your denominator is non-zero"
else:
    print "result is {}".format(result)


please enter the number1:10
please enter the number2:0
please enter numbers.Make sure your denominator is non-zero

In [12]:
# making it more granular.

try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except ZeroDivisionError:
    print "Make sure your denominator is non-zero"
except ValueError:
    print "please enter numbers."
else:
    print "result is {}".format(result)


please enter the number1:ten
please enter numbers.

In [14]:
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except ZeroDivisionError:
    print "Make sure your denominator is non-zero"
except ValueError:
    print "please enter numbers."
else:
    print "result is {}".format(result)


please enter the number1:10
please enter the number2:0
Make sure your denominator is non-zero

In [ ]:
# hhow about an exception which is not handled in the program.
# try..except..else..finally
# try -> to compute or most important task.
# except -> handling your exceptions.
# else -> if try is True.. then go to else.
# finally->
# case1: when i enter all values which are valid. -> try..else..finally
# case2: when i enter invalid value, handled by exception.-> try..except..finally
# case3: when i enter invalid values,not handed by exception -> try..finally..bombed with exception

In [17]:
#case1
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except ValueError:
    print "please enter numbers."
else:
    print "result is {}".format(result)
finally:
    print "we are all good."


please enter the number1:10
please enter the number2:2
result is 5
we are all good.

In [18]:
#case2
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except ValueError:
    print "please enter numbers."
else:
    print "result is {}".format(result)
finally:
    print "we are all good."


please enter the number1:ten
please enter numbers.
we are all good.

In [19]:
#case3
try:
    num1 = int(raw_input("please enter the number1:"))
    num2 = int(raw_input("please enter the number2:"))
    result = num1/num2
except ValueError:
    print "please enter numbers."
else:
    print "result is {}".format(result)
finally:
    print "we are all good."


please enter the number1:10
please enter the number2:0
we are all good.
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-19-db111121e3fa> in <module>()
      3     num1 = int(raw_input("please enter the number1:"))
      4     num2 = int(raw_input("please enter the number2:"))
----> 5     result = num1/num2
      6 except ValueError:
      7     print "please enter numbers."

ZeroDivisionError: integer division or modulo by zero

In [ ]:
# finally block is to make sure you can close all resource before code exits.
# db.close
# socket.close
# file.close

In [ ]:
# raise

In [20]:
pint "hello welcome "


  File "<ipython-input-20-64a359c3f7cb>", line 1
    pint "hello welcome "
                        ^
SyntaxError: invalid syntax

In [22]:
raise SyntaxError,"please clean your glasses."


  File "<string>", line unknown
SyntaxError: please clean your glasses.

In [ ]:
# if you want to raise an exception it has to be part of exception class.

In [23]:
raise santosh


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-460ec4d018fb> in <module>()
----> 1 raise santosh

NameError: name 'santosh' is not defined

In [24]:
# lets make santosh part of exception class
class santosh(Exception):
    pass

In [25]:
raise santosh,"I am back!!!"


---------------------------------------------------------------------------
santosh                                   Traceback (most recent call last)
<ipython-input-25-421375233df0> in <module>()
----> 1 raise santosh,"I am back!!!"

santosh: I am back!!!

In [26]:
#!/usr/bin/env python

age = raw_input("please enter the age 1-150:")

class InvalidAgeRangeException(Exception):
   def __init__(self,age):
     self.age = age

def validate_age(age):
     if age < 0 or age > 150:
         raise InvalidAgeRangeException(age)

# Main
try:
   age=int(age)
   validate_age(age)
except ValueError as e:
   print e
except InvalidAgeRangeException as e:
   print 'Invalid age range, you entered : %s' % e.age


please enter the age 1-150:50

In [ ]: