Exception Handling in Python (Try, Except, Else, Finally)

273

Exceptions are unexpected events and conditions that happen during runtime.

python exception handling examples
python exception handling

We will understand more about these exceptional situations in python with the help of an example –

We will consider an example of the program of an ATM Machine. With ATM machines we can do many functions such as withdrawing our balance, checking our balance, etc. But, there may occur exceptional situations like insufficient balance, or the amount user entered cannot be withdrawn because it is not a multiple of 100. Or, the amount user entered is more than the daily limit.

So, to take care of such situations, we should make our program robust. We need to write some pieces of code to take care of when such exceptional situations exist.

Writing such pieces of code that take care of such exceptions is called exception handling in python.

Try and Except Statement in Python

The Try and Except keywords are used to handle exceptions in Python. The statements that raise exceptions are kept inside the body of the try block whereas the statements that handle those exceptions are kept inside except block.

a = [1, 2, 3]
try:
 print ("Second element = %d" %(a[1]))
 print ("Fourth element = %d" %(a[3]))
except:
 print ("An error occurred")

Output –

Second element = 2
An error occurred

In the above code, first, we try to access index 1 which is present in the array and contains the value 2. So, this value is printed but when index 3 is printed, the array index out of bound condition occurs. So, the error is thrown which is caught by the except statement.

Catching Specific Exceptions in Python

A try statement can have more than one except clause, to specify handlers for different exceptions.

We will understand this with the help of the code given below –

def myfunc(a):
    if a < 4:
        b = a/(a-3)
        print("Value of b = ", b)
try:
    myfunc(3)
except ZeroDivisionError:
    print("ZeroDivisionError Handled")
except NameError:
    print("NameError Handled")

Output –

ZeroDivisionError Handled

Whereas in Another Case –

def myfunc(a):
    if a < 4:
        b = a/(a-3)
        print("Value of b = ", b)
try:
    myfunc(b)
except ZeroDivisionError:
    print("ZeroDivisionError Handled")
except NameError:
    print("NameError Handled")

Output –

NameError Handled

Try Else Clause in Python

One can also use the else clause on the try block which runs only when the try clause does not raise an exception.

We will understand this with the help of the example given below –

def AbyB(a, b):
    try:
        c = ((a+b) / (a-b))
    except ZeroDivisionError:
        print ("a/b result in 0")
    else:
        print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Output –

-5.0
a/b result in 0

Finally Keyword in Python

We can use a finally keyword that contains the code that is executed always after the try and except blocks. This piece of code always runs whether the code is normally run or after the exception handling.

We will understand this with the help of the code given below –

try:
    k = 8/0
    print(k)
except ZeroDivisionError:
    print("Can't divide by zero")
finally:
    print('This is always executed')

Output –

Can't divide by zero
This is always executed

So, in this article, we learned how to deal with the exceptions that occur during the normal flow of a program.

Attempt free Python Online Test

Python Exception Basics MCQ Test

Python Exception Coding MCQ Test

Previous articleConstructor and Destructor in Python
Next articleUser defined exceptions in Python
Harshit brijwasi Yuvayana
I am Harshit Brijwasi. I am an engineer and a Technical Content writer. I am here to share my knowledge about technical topics and help researchers with them.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.