Exception Handling in Python (Part I)

Exception Handling

Exception handling is a mechanism used to handle the abnormal situation (Exception) raised, which interrupts the normal flow of program.
Exception handling in python is similar to java but in java catch clause is used where as in python catch clause is replaced with except clause.

try….except…else

In this try block will be executed first and if error occurs then remaining try block will be skipped and except clause will be executed depending on exception raised.
Else block is optional block.

Working of try….except…else

    First,the try clause is executed ie. statements between try and except keyword.
    If no exception occurs,the except clause is skipped and execution of the try block is completed.
    If an exception occurs during execution of try clause then remaining statements of try block are skipped and control goes directly to except clause.
    If an exception occurs which does not match with the exception mentioned in except clause then control goes to remaining try block and if exception is not handled then it stops the flow of program.If else block is written then the control goes to else block before exiting.
    One try block can have multiple except clauses depending on possible exceptions to be handled.

Syntax :

try:
    statement(s)
except Exception_name:
    exception handling
else:
    if exception not matched then else will be executed
    (it is optional block)

Example of try…except block

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :27th December 2018

Description : Program to check the number entered is integer
"""
try:
    val=int(input("enter a number"))
    print("value accepted")
except ValueError:
    print("integer number expected")

Note : If user enters floating point number then control will go to except clause else it will run next statement present in try block

OUTPUT

>>> 
enter a number5
value accepted
>>> ================================ RESTART ================================
>>> 
enter a number0
value accepted
>>> ================================ RESTART ================================
>>> 
enter a number2.3
integer number expected
>>> 

Example of try…except…else block

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :27th December 2018

Description : Program to show use of try...except...else block
"""

try:
    val=int(input("enter a number"))
except ValueError:
    print("integer num expected")
else:
    print("number accepted")

Note : If user enters floating point number then control will go to except clause and if integer value is entered then control will directly go to else block by skipping except clause

OUTPUT

>>> 
enter a number2
number accepted
>>> ================================ RESTART ================================
>>> 
enter a number2.3
integer num expected

Use except with multiple attributes

Syntax :

try:
    statement(s)
except (Exception1_name,Exception2_name):
    exception handling
else:
    if exception not matched then else will be executed
    (it is optional block)

Example of except with multiple attributes

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :27th December 2018

Description : Program to show except clause with  multiple attributes
"""

try:
    val=int(input("enter a number"))
    x=100/val
except (ValueError,ZeroDivisionError):
    """ValueError exception is raised when any other value apart from integer datatype is passed
ZeroDivisionError exception is raised when we try to divide any number by 0"""
    print("non zero integer expected")
else:
    print("result is  :",x )

Note : Above program shows that one except clause can have multiple exceptions as per programming requirement

OUTPUT

>>> 
enter a number2
result is  : 50.0
>>> ================================ RESTART ================================
>>> 
enter a number2.3
non zero integer expected
>>> ================================ RESTART ================================
>>> 
enter a number0
non zero integer expected
>>> ================================ RESTART ================================
>>> 
enter a number-6
result is  : -16.666666666666668
>>> 

Use of multiple except clauses

Syntax :

try:
    statement(s)
except (Exception1_name):
    exception handling
except (Exception2_name):
    exception handling
else:
    if exception not matched then else will be executed
    (it is optional block)

Example of multiple except clauses in one program

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :27th December 2018

Description : Program to show except clause with  multiple attributes
"""

try:
    val=int(input("enter a number"))
    x=100/val
except (ValueError):
    """ValueError exception is raised when any other value apart from integer datatype is passed"""
    print("integer value expected")
except(ZeroDivisionError):
    """ZeroDivisionError exception is raised when we try to divide any number by 0"""
    print("non zero value expected")
else:
    print("result is  :",x )

Note : Above program shows that one code can have multiple except clauses
OUTPUT

enter a number5
result is  : 20.0
>>> ================================ RESTART ================================
>>> 
enter a number0
non zero value expected
>>> ================================ RESTART ================================
>>> 
enter a number-9
result is  : -11.11111111111111
>>> 

try…finally block

The finally clause is an optional block.It is used to define cleanup process that must be done under all circumstances even if exception occurs or not.

Use of try…except…else…finally clause
Syntax :

try:
    statement(s)
except (Exception1_name):
    exception handling
except (Exception2_name):
    exception handling
else:
    if exception not matched then else will be executed
    (it is optional block)
finally:
    finally block code
    (it is optional block)

Example to show use of try…except…else…finally clause

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :27th December 2018

Description : Program to show try...except...else...finally
"""
try:
    val=int(input("enter a number"))
    x=100/val
except (ValueError):
    """ValueError exception is raised when any other value apart from integer datatype is passed"""
    print("I am 1st except clause")
    print("integer value expected")
else:
    print("I am else block and i will be executed if no exception is raised")
    print("result is  :",x )
finally:
    print("I am finally block and i will be executed even if exception is raised or not")

Note : Above program consist of finally block which will be executed irrespective of exception being raised or not

OUTPUT

>>> 
enter a number5.2
I am 1st except clause
integer value expected
I am finally block and i will be executed even if exception is raised or not
>>> ================================ RESTART ================================
>>> 
enter a number5
I am else block and i will be executed if no exception is raised
result is  : 20.0
I am finally block and i will be executed even if exception is raised or not
>>> 

Example for try…except…else…finally with multiple except clause

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :27th December 2018

Description : Program to show try...except...else...finally
"""
try:
    val=int(input("enter a number"))
    x=100/val
except (ValueError):
    """ValueError exception is raised when any other value apart from integer datatype is passed"""
    print("I am 1st except clause")
    print("integer value expected")
except(ZeroDivisionError):
    """ZeroDivisionError exception is raised when we try to divide any number by 0"""
    print("I am 2nd except clause")
    print("non zero value expected")
else:
    print("I am else block and i will be executed if no exception is raised")
    print("result is  :",x )
finally:
    print("I am finally block and i will be executed even if exception is raised or not")

OUTPUT

>>> 
enter a number1
I am else block and i will be executed if no exception is raised
result is  : 100.0
I am finally block and i will be executed even if exception is raised or not
>>> ================================ RESTART ================================
>>> 
enter a number0
I am 2nd except clause
non zero value expected
I am finally block and i will be executed even if exception is raised or not
>>> ================================ RESTART ================================
>>> 
enter a number1.5
I am 1st except clause
integer value expected
I am finally block and i will be executed even if exception is raised or not

Exception with an argument

An exception is having an argument.An argument is a value that provides additional information about the problem.
As exception changes the value of that argument also changes.To store the value of an argument we can use a variable.

Syntax :

try:
    statement(s)
except Exception1_name as argument:
    you can print value of the argument

Here,
argument can be any variable name
as is a keyword used to assign an argument name
Explaination
If single exception is given in except clause than there will be a variable acting as an argument to hold the value of exception.
If we want to give multiple exceptions we can give them in a tuple and then give a variable name as a argument.
Sometimes this variables will receive values in form of tuples based on different exceptions.

Example to show single exception as argument

try:
    val=int(input("enter a num"))
    result=100/val
except Exception as e:
    print("the argument is having value as", e)
    print("exception",type(e))
else:
    print("no exception so result is",result)

OUTPUT

>>> 
enter a num5
no exception so result is 20.0
>>> ================================ RESTART ================================
>>> 
enter a num0
the argument is having value as division by zero
exception <class 'zerodivisionerror'="">
>>>

Leave a Comment