Tuesday, April 28, 2020

Exception Handling


What is Exception:

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.

Sample Code:

a=10
b="Zelda"
print(a+b)

Output:

=RESTART: E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py
Traceback (most recent call last):
  File "E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py", line 4, in <module>
    print(a+b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 
When trying to add integer and string, the execution of the program is terminated abruptly and error is raised. This error is called exception.

  
How to handle exception:

If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code which handles the problem as elegantly as possible

Basic Example

try:
  a=10
  b="Zelda"
  print (a+b)
except:
  print ('Exception occured')


Output:
>>>
= RESTART: E:\Software\Google Drive\SOMEFOLDER\BATCH-A\learningExceptionHandling.py
Exception occured
>>> 


In the below example, exception is raised based on the type of exception.
There are two type of exception is handled.
a.   TypeError
b.   ZeroDivisionError

Based on the nature of the error we can handle it in the respective except block.

Try:
  a=10
  b=0#change this to string so that we get TypeError
  print (a+b)
  print (a/0)
except  TypeError as e:
  print (e)
except  ZeroDivisionError as e:
  print(e)


1)           try>except

In the below example, if the exception is occurred and if it not handled properly then again the program is terminated abruptly.

Try:
  a=10
  b=0
  print (a/b)
except  TypeError as e:
  print (e)

= RESTART: E:\Software\Google Drive\SOMEFOLDER\BATCH-A\learningExceptionHandling.py
Traceback (most recent call last):
  File "E:\Software\Google Drive\SOMEFOLDER\BATCH-A\learningExceptionHandling.py", line 4, in <module>
    print (a/b)
ZeroDivisionError: division by zero
>>>
 
In this example there is zero division error and exception is handled for TypeError.

2)           try>except>else

a)
try:
  a=10
  b='1'
  print (a+b)
except  TypeError as e:
  print (e)
else:
  print('Else') #This  Will only execute when there are no Errors

When the try block  code is executed, there is a TypeError. Hence the else block will not executed.

Output: >>>
= RESTART: E:\Software\Google Drive\SOMEFOLDER\BATCH-A\learningExceptionHandling.py
unsupported operand type(s) for +: 'int' and 'str'
>>> 


b)
try:
  a=10
  b=1
  print (a+b)
except  TypeError as e:
  print (e)
else:
  print('Else') #This  Will only execute when there are no Errors

a.   When executing the above code , both section of code i.e. code in try block and else block will execute as there is not error.

Output:
>>>
= RESTART: E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py
11
Else
>>> 

Conclusion:
b.   If there is no exception occurred, then both try and else block will executed.
c.    If there is exception then else block will NOT execute

3)          try>except>finally


a) When exception is occurred in try block.

try:
  a=10
  b=’1’
  print (a+b)
except  TypeError as e:
  print (e)
finally:
  print('Else') #This  will always  execute even if there are not errors




Output:
>>>
= RESTART: E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py
unsupported operand type(s) for +: 'int' and 'str'
Finally
>>> 

The except code block and finally code block both are executed.

b) When  there is no exception  occurred in try block.

try:
  a=10
  b=1
  print (a+b)
except  TypeError as e:
  print (e)
finally:
  print('Else') #This  will always  execute even if there are not errors

Output:

>>>
= RESTART: E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py
11
Finally
>>> 

Finally code block will execute even if there are no error in try block.

  1. 4)   try>finally


a)   When there are NO exception in try block
try:
  a=10
  b=’1’
  print (a+b)
finally:
  print('Else') #This  will always  execute even if there are not errors






Output:
>>>
= RESTART: E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py
11
Finally
>>> 

The finally code block is executed

b)           When there are exception in the try block

try:
  a=10
  b=’1’
  print (a+b)
finally:
  print('Else') #This  will always  execute even if there are not errors

Output:
>>>
= RESTART: E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py
Finally
Traceback (most recent call last):
  File "E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py", line 4, in <module>
    print (a+b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 

The finally code block still execute along with the error.

5)   try>except>else>finally

You need to try this
=======================


How to Raise an Exception

try:
  a=10
  b=1
  if b==1:
     raise Exception("Denominator cannot be 1")# program terminates
  else:
    print (a+b)

finally:
  print(‘Finally’)

The above program terminates when the condition is satisfied.

So basically if you want to abruptly terminate the program, based on some known condition, we can raise the exception. 

>>> 
= RESTART: E:\Software\Google Drive\SOMEFOLDER\BATCH-A\learningExceptionHandling.py
Finally
Traceback (most recent call last):
  File "E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py", line 6, in <module>
    raise Exception("Denominator cannot be 1")
Exception: Denominator cannot be 1
>>> 

How to Raise an Exception

try:
  a=10
  b=1
  if b==1:
     raise Exception("Denominator cannot be 1")# program terminates
  else:
    print (a+b)

finally:
  print(‘Finally’)

The above program terminates when the condition is satisfied.
So basically if you want to abruptly terminate the program, based on some known condition, we can raise the exception.



User Defined Exceptions

Class   MyError(Exception):

  def  __init__(self,msg):
    If msg==1:
      self.message="Denominator cannot be 1"
    elif msg==2:
      self.message="Denominator cannot be 2"


try:
  a=10
  b=1
  if b==1:
     raise MyError (1) #When b is equal to 1 then raise this error
  elif b==2:
     raise MyError (2) #When b is equal to 2 then raise this error
  else:
    print (a+b)

except MyError as m:
  print(m.message)
finally:
  print(‘Finally’)






Assertions in Python:

An assertion is a sanity-check that you can turn on or turn off when you are done with
your testing of the program.

The easiest way to think of an assertion is to liken it to a raise-if statement (or to
be more accurate, a raise-if-not statement). An expression is tested, and if the
result comes up false, an exception is raised.

assert(1==2)

If the above condition fails an exception of AssertionError is raised.

Output:
>>>
= RESTART: E:\Software\Google Drive\SOMEFOLDER\BATCH-A\learningExceptionHandling.py
Traceback (most recent call last):
  File "E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py", line 1, in <module>
    assert(1==2)
AssertionError
>>> 

In nutshell assert only raise exception when expression is false.

assert(False)

>>>
= RESTART: E:\Software\Google Drive\SOMEFOLDER\BATCH-A\learningExceptionHandling.py
Traceback (most recent call last):
  File "E:\Software\Google Drive\PRWATECH\BATCH-A\learningExceptionHandling.py", line 1, in <module>
    assert(False)
AssertionError
>>> 


Difference between Raise and Assert.

1)    Raise : We can raise custom error based on the condition.

raise myError(“My Error Message/Arguments”)

2)    Assert(false),”My Error Message”


In a nutshell

assert condition, "text"

is similar to;

If   condition == False:
  raise AssertionError("text")











No comments:

Post a Comment