In [ ]:
# exception handling
# how do we deal with errors.
# ex: ValueError,ZeroDivisionError
# try..except..else..finally
# try -> it hold the code which is mandatory.
# except -> what you want to do with your exceptions
# else -> if all is good in try block , lets go for the else block.

In [1]:
# example1

num1 = int(raw_input("please enter your num1:" ))
num2 = int(raw_input("please enter your num2:" ))
result = num1/num2
print "the result of our operation is {}".format(num1/num2)


please enter your num1:10
please enter your num2:2
the result of our operation is 5

In [2]:
# use case I : error 1
num1 = int(raw_input("please enter your num1:" ))
num2 = int(raw_input("please enter your num2:" ))
result = num1/num2
print "the result of our operation is {}".format(num1/num2)


please enter your num1:ten
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-c626ba2893ea> in <module>()
      1 
----> 2 num1 = int(raw_input("please enter your num1:" ))
      3 num2 = int(raw_input("please enter your num2:" ))
      4 result = num1/num2
      5 print "the result of our operation is {}".format(num1/num2)

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

In [3]:
# Use case : Error2
num1 = int(raw_input("please enter your num1:" ))
num2 = int(raw_input("please enter your num2:" ))
result = num1/num2
print "the result of our operation is {}".format(num1/num2)


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

ZeroDivisionError: integer division or modulo by zero

In [4]:
# python comes with a set of exceptions.
# Can we create our own exception - yes
import exceptions as e
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 [9]:
# exception handling
try:
    num1 = int(raw_input("please enter your num1:" ))
    num2 = int(raw_input("please enter your num2:" ))
    result = num1/num2
except:
    print "please enter numbers and make sure your denominator is non-zero"
else:
    print "the result of our operation is {}".format(num1/num2)


please enter your num1:10
please enter your num2:2
the result of our operation is 5

In [10]:
# exception handling - we want to only handle the exception below.
# ZeroDivisionError,ValueError

try:
    num1 = int(raw_input("please enter your num1:" ))
    num2 = int(raw_input("please enter your num2:" ))
    result = num1/num2
except (ZeroDivisionError,ValueError):
    print "please enter numbers and make sure your denominator is non-zero"
else:
    print "the result of our operation is {}".format(num1/num2)


please enter your num1:ten
please enter numbers and make sure your denominator is non-zero

In [13]:
# exception handling - we want to only handle the exception below.
# ZeroDivisionError,ValueError

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


please enter your num1:10
please enter your num2:0
Please make sure your denominator is non-zero.

In [14]:
# try..except..else..finally
# try -> it hold the code which is mandatory.
# except -> what you want to do with your exceptions
# else -> if all is good in try block , lets go for the else block.
# finally -> 
# case 1: All values are valid - try..else..finally
# case 2: i enter invalid values , but handled by exceptions - try..except..finally
# case 3: i enter invalid values, but not handled by exception - try..finally..exception

In [17]:
try:
    num1 = int(raw_input("please enter your num1:" ))
    num2 = int(raw_input("please enter your num2:" ))
    result = num1/num2
except ValueError:
    print "please enter numbers."
else:
    print "the result of our operation is {}".format(num1/num2)
finally:
    print "All is Well !!!" # close your files,databases,sockets


please enter your num1:10
please enter your num2:0
All is Well !!!
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-17-f0176ee5d243> in <module>()
      2     num1 = int(raw_input("please enter your num1:" ))
      3     num2 = int(raw_input("please enter your num2:" ))
----> 4     result = num1/num2
      5 except ValueError:
      6     print "please enter numbers."

ZeroDivisionError: integer division or modulo by zero

In [18]:
# raise
raise SyntaxError


  File "<string>", line unknown
SyntaxError

In [19]:
raise SyntaxError,"Hey there clean your glasses"


  File "<string>", line unknown
SyntaxError: Hey there clean your glasses

In [20]:
# We can build our own exception.
# you cannot raise all words, the key should be a part of exception class.

In [21]:
raise santosh # is not part of your exception class.


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

NameError: name 'santosh' is not defined

In [23]:
# santosh is a cusotmized exception.
class santosh(Exception):
    pass

raise santosh,"I am back!!!"


---------------------------------------------------------------------------
santosh                                   Traceback (most recent call last)
<ipython-input-23-fb9ebebc131d> in <module>()
      2     pass
      3 
----> 4 raise santosh,"I am back!!!"

santosh: I am back!!!

In [ ]: