Wednesday, November 28, 2018

Python Ninja bootcamp 29-Error & Exception(try, except & finally)

Learn Python like a Professional! Take You from 0 to Hero






In this Python lecture, we will learn about the Error & Exception(try, except & finally).



"When Python encounters error while running the code, it stops execution and raises an exception".


Let's see some example-

Error & Exception 


1/0
>>ZeroDivisionError: division by zero
1 + 'string'
>>TypeError: unsupported operand type(s) for +: 'int' and 'str'
if 2<3
    print('Hi')
>>SyntaxError: invalid syntax


Try, except,else & finally


def division(a,b):
    try:
        result=a/b
    except Exception:
        print("Sorry! Division is not possible")
    else:
        print("sum of a and b =",result) 


division(1,0) 
>>Sorry! Division is not possible

def division(a,b):
    try:
        result=a/b
    except Exception as e:
        print(e)
    else:
        print("sum of a and b =",result)

division(1,0)
>>division by zero


def division(a,b):
    try:
        result=a/b
    except Exception as e:
        print(e)
    else:
        print("sum of a and b =",result)


division(1,'string')
>>unsupported operand type(s) for /: 'int' and 'str'

def division(a,b):
    try:
        result=a/b
    except Exception as e:
        print(e)
    else:
        print("sum of a and b =",result)

division(1,2)
>> sum of a and b = 0.5

def division(a,b):
    try:
        result=a/b
    except Exception as e:
        print(e)
    else:
        print("sum of a and b =",result)
    finally:
        print("Executing finally block.....")

division(1,2)
>> sum of a and b = 0.5
     Executing finally block.....
division(1,0)
>> division by zero
     Executing finally block.....

EDITS ARE WELCOMED!!

In the next Blog, we will discuss Q&A 5th 

https://sngurukuls247.blogspot.com/2018/12/python-ninja-bootcamp-30-q-5th.html

......................................................................................................................................

Follow the link below to access Free Python Lectures-
https://www.youtube.com/channel/UCENc9qI7_r8KMf6-_1R1xnw

Instagram
https://www.instagram.com/python.india/
 

View the Jupyter Notebook for this lecture

Download the Jupyter Notebook for this lecture 




Feel free contact me on-
Email - sn.gurukul24.7uk@gmail.com

No comments:

Post a Comment