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.

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