Exception handling in python.

Exception handling in python.

EXCEPTIONAL HANDLING IN PYTHON.

What are errors in python?

Syntax errors : These errors are generated by wrong syntax in python . for example

1K = 199
print(1K)

output:
    1K = 199
     ^
SyntaxError: invalid syntax

There is another error names logical error in which error arrises due to wrong logic in code. These are most diificult error as python didnot return any error and coder may find difficulty in finding the error.

What are exceptions?

Exceptions arrises when your code is syntactcally correct but the code result an error. This willresult in breaking the flow of program.

x=100
y=x/0   #this will return error as it is being divided by 0 .
print(y)

output:
y=x/0   #this will return error as it is being divided by 0 .
ZeroDivisionError: division by zero

To overcome the problems we use exceptional handling .

Try and Except statement in python.

These are used to catch any exception in the code. Expressions the can raise exceptions in the try clause are kept and user generated output will be given in place of error. for ex.

try:
    100/0
except:
    print("No error LOL")

output:
No error LOL

Try and Except with Else statement.

Try and except with else statement is used to handle those type of problems in which we need the code to execute to fullest .For ex:

def div(a,b):
    try:
        c=a/b
    except:
        print("zero division error")
    else:
        print(c)
div(2,5)
div(5,0)
div(5,5)

output:0.4
       zero division error
       1.0

Finally Keyword.

The statement or expression inside the finally keyword will always be executed. For ex.

def div(a,b):
    try:
        c=a/b
        print(c)
    except:
        print("zero division error")
    finally:
        print("I will execute everytime :-)")
div(4,2)
div(4,0)

output:
2.0
I will execute everytime :-)
zero division error
I will execute everytime :-)

#THANKYOU