Tuesday, 28 January 2020

Exception Handling Part 2

#If there is no exception
try:
    print("Statement 1")
    print("Statement 2")
    print("statement 3")
except ZeroDivisionError:
    print("Statement 4")
finally:
    print("Statement 5")
print("Statement 6")

"""output:
Statement 1
Statement 2
statement 3
Statement 5
Statement 6

Note: If there is no exception, all the statements will be executed, but not except block
"""
Case 2:#If there is exception at statement 2
try:
    print("Statement 1")
    print(10/0)#statement 2 : exception
    print("statement 3") #Not executed
except ZeroDivisionError:
    print("Statement 4")
finally:
    print("Statement 5")
print("Statement 6")

"""output:
Statement 1
Statement 4
Statement 5
Statement 6
Note: If any exception raised within the try block, rest of the try block statements are not executed.
"""

Case 3:#If there is an exception at st 2, but the corresponding exception is not matched
try:
    print("Statement 1")
    print(10/0)#statement 2 : exception
    print("statement 3")
except TypeError:
    print("Statement 4")
finally:
    print("Statement 5")
print("Statement 6")

"""output:
Statement 1
Statement 5
Abnormal termination
"""
#Case 4:If there is exception at st 2
try:
    print("Statement 1")
    print(10/0)#statement 2 : exception
    print("statement 3")
except TypeError:
    print("Statement 4")
except ZeroDivisionError:
    print("Zero Division is not possible")
finally:
    print("Statement 5")
print("Statement 6")

"""output:
Statement 1
Zero Division is not possible
Statement 5
Statement 6

#Case 4:If there is exception at st 2, and exception is in except block
try:
    print("Statement 1")
    print(10/0)#statement 2 : exception
    print("statement 3")
except TypeError:
    print("Statement 4")
except ZeroDivisionError:
    print(2/0)#Exception
finally:
    print("Statement 5")
print("Statement 6")

"""output:
Statement 1
Statement 5
Abnormal Termination
"""
Note: Exception is at statement 2 and also in except block, in addition, to try block, there may be a chance of raising exception inside except and finally block also, it leads to abnormal termination.
"""
#Case 5:If there is no exception in try block
try:
    print("Statement 1")
    print(10/2)#statement 2
    print("statement 3")
except TypeError:
    print("Statement 4")
except ZeroDivisionError:
    print(2/0)#Exception
finally:
    print("Statement 5")
print("Statement 6")

"""output:
Statement 1
5.0
statement 3
Statement 5
Statement 6
"""
#Case 6:exception is raised out side the try block, which leads to abnormal
#termination
try:
    print("Statement 1")
    print(10/2)#statement 2
    print("statement 3")
except TypeError:
    print("Statement 4")
except ZeroDivisionError:
    print("Statement 5")
finally:
    print("Statement 6")
print(10/0)#st 7

"""output:
Statement 1
5.0
statement 3
Statement 6
Abnormal termination
"""
#Multiple except blocks
try:
    a=int(input("enter a value"))
    b=int(input("enter b value"))
    print(a/b)
except ZeroDivisionError:
    print("b=",b,"should not be zero")
except ValueError:
    print("Enter integer only")
"""output:
Case1:
enter a value4
enter b value2
2.0
Case 2:
enter a value4
enter b value0
b= 0 should not be zero
Case 3:
enter a value4
enter b valuetwo
Enter integer only
"""
Combination except blocks also can be written
#Multiple except blocks
try:
    a=int(input("enter a value"))
    b=int(input("enter b value"))
    print(a/b)
except (ZeroDivisionError,ValueError):
    print("b=",b,"should not be zero")
    print("Enter integer only")

"""output:
Case1:
enter a value4
enter b value2
2.0
Case 2:
enter a value4
enter b value0
b= 0 should not be zero
Case 3:
enter a value4
enter b valuetwo
Enter integer only
"""
Default exception:
We can use default except block to handle any type of exceptions.
#default except
try:
    a=int(input("enter a value"))
    b=int(input("enter b value"))
    print(a/b)
except ZeroDivisionError:
    print("b=",b,"should not be zero")
except: #default exception
    print("Enter integer only")

"""output:
Case1:
enter a value4
enter b value2
2.0
Case 2:
enter a value4
enter b value0
b= 0 should not be zero
Case 3:
enter a value4
enter b valuetwo
Enter integer only
"""
    Related Video: https://youtu.be/dq9W6ig91QQ

Next: Exception Handling 3
Prev:Exception Handling part1
https://youtu.be/oC6v7WLzZFw

assert keyword



Assert keyword

18th Feb,2020.

Debugging:
Identifying and solving the errors (bugs) is called debugging.

Debugging:
Identifying the bug/issues (error) and solving (fixing) the issue/bug/errors is called Debugging.

Assert keyword:
def addition(a,b):
    return a-b
assert addition(4,2)==6,"Addition of two number=6"
assert addition(3,2)==5,"Addition of 3,2 is 5"
print("Addition of 4,2 numbers",addition(4,2))
print("Addition of 3,2 numbers",addition(3,2))
"""output:
assert addition(4,2)==6,"Addition of two number=6"
AssertionError: Addition of two number=6

Addition of 4,2 numbers 2
Addition of 3,2 numbers 1
"""
If I’m not using the assert in the above program, wrong output may be handed over to the client, because of the assert, it verifies the expected output other wise it will alert to the programmer.
def addition(a,b):
    return a+b
assert addition(4,2)==6,"Addition of two number=6"
assert addition(3,2)==5,"Addition of 3,2 is 5"
print("Addition of 4,2 numbers",addition(4,2))
print("Addition of 3,2 numbers",addition(3,2))
"""output:
Addition of 4,2 numbers 2
Addition of 3,2 numbers 1

Addition of 4,2 numbers 6
Addition of 3,2 numbers 5

Assert keyword is used to debugging (i.e resolving the error)
We will perform debugging in development environment or in the testing environment but not in the production environment.
Types of assert statements:
1.   Simple version
2.   Augmented version
Simple version:
Assert conditional expression



Augmented version:
Assert conditional expression, any message
Example: assert addition(4,2)==6,"Addition of two number=6"
Handling the AssertionError :

#example program on handling the assertion Error
def avg(marks):
    try:
        assert len(marks)!=0
        return sum(marks)/len(marks)
    except AssertionError:
        print("Marks are empty")
stud1=[]
print("Average of stud1",avg(stud1))
stud2=[60,88,70,90]
print("Average of stud1",avg(stud2))

len() is a predefined function in python, It is used to find the length of the given string,array,list,tuple, dictionary,..etc. The number of elements stored in the list, it displays.

What is the difference between Exception handling and assertions?
Assertion is used to alert or warning to the programmer to resolve the development bugs/issues. Where as exception handling is used to handle runtime errors.

Related Video: https://youtu.be/UORaySj-M2w
Next: Example program on class and object
Previous: else with try and nested exception blocks

example program on constructors


Constructor:
class emp:
##constructor
    def __init__(self,name,id,sal):
        self.id=id
        self.name=name
        self.sal=sal
## defining the method      
    def display(self):
        print("empid:%d\n ename:%s\nsalary:%f"%(self.id,self.name,self.sal))
e1=emp("ravi",10,1500)
e2=emp("sita",20,2500)
e1.display()
e2.display()
"""output:
empid:10
 ename:ravi
salary:1500.000000
empid:20
 ename:sita
salary:2500.000000"""
  It is a special method, it is called automatically as soon as the object is created. Constructor are used to initialise the data into the object.
No need to call the constructors, once object the object is created, it is called automatically.
There are two types of constructors:
1.   Parameterised constructor
2.   Non-parameterised constructor
  Parameterised constructor: if atleast one parameter is there is called parameterised constructor.
Ex:
def __init__(self,id,name,sal):
….
Ex: E1=emp(10,’sita’,1500)
Non-parameterised constructor:
If there is no parameter in the constructor then it is called non-parameterised constructor. Except ‘self’ keyword.
Ex:
def __init__(self):
….
e.display()





Related Video: https://youtu.be/cm7EW6q-tR0
Next:
Previous: Example program on class and object

Exception Handling part 1


#example program on without Exception Handling
print("Good afternoon")#
print(4/2)#
print(10/0)#exception raised
print("Thank you")
output:
Good afternoon
2.0
Runtime error : Abnormal termination
with using try..except
#example program on Exception Handling
print("Good afternoon")#
print(4/2)#
try:
    print(10/0)#exception raised
except ZeroDivisionError:
    print("division by zero is not possible")
print("Thank you")
Ouput:
Good afternoon
2.0
Division by zero is not possible
Thank you

Exception:

An exception is on error, which can occur during runtime and which can be handled by the programmer. That means if programmer can guess an error in the program and he can avoid the abnormal termination by using try..except keywords.

Types of exceptions
1.   Predefined exception (built in exceptions)
2.   User defined exceptions
Predefined exception are represented as classes.

Purpose Exception Handling:
To make the program more powerful (robust=strong). If we are handling the exceptions, our program/application will not terminate abnormally during execution.

Steps to handling the exceptions:
1.   As a programmer should observe the code where there may be possible of exceptions, such exceptions should be kept in side the try block.
Example:
       try:
                   10/0  #risky code

2.   We should write the corresponding exception class name with except keyword. This step is called handling the exception
Ex: except for DivisionByZero:
                   Any message
3.    finally, this keyword is used to clean up the code example closing the files.
Whenever we write the statements in side the finally block, those statements will be executed irrespective of the exceptions.
The above 3 steps are called the exception handling.
Syntax:
try:
          Risky code /Run this code
except NameOfexception:
          run this code if exceptions occur in the try block

#Example program
def concat(a,b):
    print(a+b)
try:
    concat("hyd",25)
    print("good morning")
except TypeError:
    print("Only strings can be concatinated but not one string, one number")

"""output:
Case1
Only strings can be concatenated but not one string, one number
>>>

Case2: If you want to execute the statement irrespective of exception, use finally block
def concat(a,b):
    print(a+b)
try:
    concat("hyd",25)#exception raised
except TypeError:
    print("Only strings can be concatinated but not one string, one number")
finally:
    print("good morning")

"""output:
Only strings can be concatenated but not one string, one number
good morning

Case3: exception can be more than one but try should be only one
def concat(a,b):
    print(a+b)
try:
    concat("hyd",25)#exception raised
    print(10/0)
except TypeError:
    print("Only strings can be concatinated but not one string, one number")
except ZeroDivisionError:
    print("Division by zero is not possible")
finally:
    print("good morning")

"""output:
Case2
Only strings can be concatenated but not one string, one number
good morning

Related video: https://youtu.be/oC6v7WLzZFw

Nexthttps://youtu.be/dq9W6ig91QQ

Prev:Exceptions:
https://youtu.be/TeVaBIo-WQo

Example program on class and object




Next:Example program on constructors
Previous:Assert keyword
https://youtu.be/UORaySj-M2w

Nested try block and else block


try:
    print("outer try block")
    try:
        print("inner try block")
        print(2/0) #exception raises here, and corresponding except is matched
    except ZeroDivisionError:
        print("inner except block")
    finally:
        print("inner finally block")
except:
    print("outer except block")
finally:
    print("outer finally block")

"""output:
outer try block
inner try block
inner except block
inner finally block
outer finally block
>>>
"""
We can take try-except-finally blocks inside try or except or finally blocks it is called nesting exception handling.
Generally risky code we have to take inside outer try block and too much risky code we have to take inside inner try block.

·       Inside inner try block if an exception raised then except block is responsible to handle.  If it unable to handle then outer except block is responsible to handle.

Syntax:
try:
      ……
      ……
      try:
       ……..
       ………
       except:
       ……..
       ………
except:
      ……
      ……

#example program on nested try-except finally block
try:#outer try block
    print("statement1")
    print(4/2)#statement2 5.0
    print(10/5)#statement3 5.0
    try: #inner try block
        a=int(input("enter a value ")) #4
        b=int(input("enter b value ")) #"two"
        print("statement 4")
        print(a/b)#statement 5 #exception is raised
        print("statement 6")
    except ValueError:#inner exception block
        print("enter int only")#statement 7
    finally:#inner finally block
        print("statement 8")
        print("statement 9")
except ZeroDivisionError: #outer except block
        print("Zero Division is not possible")#statement 10
finally:
    print("statement 11")
print("statement 12")
"""
output:
statement1
2.0
2.0
enter a value 4
enter b value 0
statement 4
statement 8
statement 9
Zero Division is not possible
statement 11
statement 12
case 2:
statement1
2.0
2.0
enter a value 4
enter b value two
enter int only
statement 8
statement 9
statement 11
statement 12

"""
else block with try-except finally block
#example progrm on else block with try-except finally block
try:
    a=int(input("enter a value "))
    b=int(input("enter b value "))
    print("hi")
    print(a/b)
except ZeroDivisionError:
    print("except block")
else:
    print("else block")
finally:
    print("finally block")
"""output:
Case 1:
enter a value 2
enter b value 1
hi
2.0
else block
finally block
case 2:
enter a value 4
enter b value 0
hi
except block
finally block
"""
 We can use else block with try-except finally blocks. Else block will be executed if and only if there are no exception inside try block.

Syntax:
try:
          Risky code:
except:
          It executes if any exception occur in the try block
else:
          It executes if there is no exception in the try block
finally:
          It executes always
Note:
1.   For every else block, except block is mandatory.
Example:
try:
    a=int(input("enter a value "))
    b=int(input("enter b value "))
    print("hi")
    print(a/b)
else:  #Error
    print("else block")
2.   Order of try-except-else-finally is important
3.   Without try block, we can not write finally block
Example:
try:
….
finally:
 ……


Nexthttps://youtu.be/UORaySj-M2w
assert keyword

Previous:


Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...