Exception Handling in Python

                 Exception Handling

Exceptions can be defined as the error which causes the interuption in the flow of program and program do not terminate normally. Exceptions are the run time errors but like any other advanced programming languages Python can also handle the exceptions. There can be different types of exeptions like -

Arithmetic Exception
Assertion Exception
Import Exception
Memory Exception
Name Exception
OS Exception
etc...
These main exceptions have also many types of exception subclasses.

How to handle exceptions ?
try-except : 
In try block we write the code which is to be executed or attempted. If we have any code which can generate the exceptions then we place it to the try block. except block contains the code which is to be executed if there is any exception in the try block.

E.g.  try:
        a = 5/0
    except Exception as e:
        print(e)
        
        Output : division by zero

In above code we have written "except Exception as e". It means that we are using Exception in the form of e. Think of it as an alias. It is upto us whether we want to use it or not. In above code we have used the default exception message using the e, but if we want we can use our own message. Let's see how - 
        try:
        n = int(input("enter the number: "))
    except ValueErrror:
        print("That is not an integer")

    Output: enter the number: one
                     This is not an integer

We can also use the else block with try-except which will execute if there is not execption occurred in try block.
        try:
        n = 5/2
    except Exception as e:
        print(e)
    else:
        print(n)
        
        Output: 2.5

finally:
We can use the finally block also with try-except block. finally block will always exceute the code inside it whether there is an exception or not. 
    
E.g.  try:
        a = int(input("enter the number : "))
        c = 10/a
    except Exception as e:
        print(e)
    else:
        print(c)
    finally:
        print("This is finally block")
    
        Output : enter the number : 0
                          division by zero
                          This is finally block
        
                          enter the number : 2
                          5.0
                          This is finally block

Throwing Exceptions : 
We can make our own program exception. We can raise the exception under certain conditions if we want. To raise the exceptions we use raise keyword followed by the exception class name.

E.g.  a = 1
    def RaisingExceptions(a):
        if type(a) != type('a'):
            raise ValueError("This is not string")
    try:
        RaisingExceptions(a)
    except ValueError as e:
        print(e)
        
        Output : This is not string 

Comments

Popular posts from this blog

Loops in Python

Python OOPs

Regular Expressions