09. Exception Handling

Exception

Errors are exceptional, unusual and unexpected situations and they are never part of the normal flow of a program. We need a process to identify and handle them to write a good program. Exception handling is the process of responding in such situations. Most of the modern programming languages provide support with handling exceptions. They offer a dedicated exception handling mechanism, which simplifies the way in which an exception situation is reported and handled.

For example:
a=10
b=0
c=a/b
ZeroDivisionError: division by zero #its celled exception

System Define Error

Before moving further, let's talk of some of the python's predefined error types, which we can use with raise statement. This does not mean that raise can't be used to raise user defined errors.

S.No

Error type

Description

1

IOError

is raised when I/O operator fails. Eg. File not found, disk full

2

EOFError

is raised when, one of the file methods i.e. read(), readline() or readlines(), try to read beyond the file.

3

ZeroDivisionError

is raised when, in division operation, denominator is zero

4

ImportError

is raised when an import statement fails to find the module definition or file name

5

IndexError

is raised when in a sequence - index/subscript is out of range.

6

NameError

is raised when a local or global name is not found

7

IndentationError

is raised for incorrect indentation

8

TypeError

is raised when we try to perform an operation on incorrect type of value

9

ValueError

is raised when a built in function/method receives an argument of correct type but with inappropriate value.

Exception Handling

Exception handling will improve the reliability of application program. Python creates different type of objects in case of different exceptional conditions that describes the cause of exception.

Exception handling is done by try-except-finally block. The try may have multiple except blocks. Exception raised in try block is caught by except block. Block finally is optional and always executed.

Syntax:

try:
    pass
except ExceptionType :
    pass
else:
    pass
finally:
    pass

try-except

we can handle error using try-except :

For Example:

try:
    print(1/0)

except ZeroDivisionError:
    print("You can't divide by zero")

Output:
You can't divide by zero

try-except-else

The else clause written after all except statements, is executed, if code in try block does not raise any exception.

For example:

try:
    num1 = int(input("Enter First Number: "))

    num2 = int(input("Enter Second Number: "))

    num3 = num1/num2;

    print("num1/num2 = ",num3)

except ZeroDivisionError:
    print("can't divide by zero")

else:
     print("no exception generated")

Output:
Suppose if you divide 10/5
no exception generated

try-except-finally

finally clause is always executed before leaving the try statement irrespective of occurrence of exception. It is also executed if during execution of the try and except statement any of the clause is left via break, continue or return statement.

For Example:
try:
    num1 = int(input("Enter First Number: "))

    num2 = int(input("Enter Second Number: "))

    num3 = num1/num2;

    print("num1/num2 = ",num3)

except ZeroDivisionError:
    print("can't divide by zero")

finally:
     print("I am always executed")

Custom Error

we can generate custom error using raise keyword in python

For Example:
class LoginException(Exception):

    def __init__(self):
    super(LoginException,self).__init__("invalid User")

class Custom(LoginException):
    def authenticate(self,user_id,pwd):
        if user_id.__eq__("admin") and pwd==1234 :
            print("Login Successfully")
        else:
            raise LoginException

c=Custom()

c.authenticate("admi",1234)

Output:
LoginException invalid User