Exception Handling in Python

This article will walk you through the process of handling exceptions in Python by utilizing the try, except, and finally statements, along with some useful examples.

There are two different kinds of problems that can occur in Python: syntax errors and exceptions. Errors are difficulties that occur within a program and are the reason why the program will halt its execution when an error occurs. On the other hand, exceptions are thrown if a normal flow of the program is disrupted by certain happenings within the program itself.

The Difference between Exceptions and Syntax Errors

Error in Syntax: As its name suggests, this type of error is brought on by incorrect syntax anywhere inside the code. It ultimately results in the conclusion of the program.


# initialize the amount variable

amount = 10000

 # check that You are eligible to

# purchase Dsa Self Paced or not

if(amount > 2999)

print("You are eligible to purchase Dsa Self Paced")

Exceptions: An exception is thrown whenever a program is syntactically correct but the code produced an error. Exceptions are raised when a program’s syntax is proper but the code produces an error. Although the execution of the program is not terminated as a result of this error, the usual flow of the program is disrupted.


# initialize the amount variable

marks = 10000

 # perform division with 0

a = marks / 0



The above example resulted in the generation of a ZeroDivisionError since we attempted to divide a number by 0. Note that the Exception class serves as the foundation for all exceptions in Python.

 Try and Except Statement – Catching Exceptions.

In Python, catching and handling exceptions is accomplished through the usage of the try and except commands. Statements that have the potential to throw an exception are contained within the try clause, and the statements that are responsible for handling the exception are written within the except clause.
Example: Let’s attempt to access the array member whose index is outside the allowed range and then deal with the exception that results from doing so.

# Python program to handle simple runtime error

#Python 3

 a = [1, 2, 3]

   print ("Second element = %d" %(a[1])) 
# Throws error since there are only 3 elements in array
   print ("Fourth element = %d" %(a[3])) 
   print ("An error occurred")

The statements that have the potential to generate an error are contained within the try statement in the preceding illustration (second print statement in our case). An exception is generated as a result of the fact that the second print statement attempts to access the fourth element of the list, which does not exist. Unless statement will then take care of this unforeseen circumstance.

During the course of the execution of a program, undesirable events known as errors and exceptions can occur. However, there are significant distinctions between the two. The programmer can prepare for and anticipate exceptions, but it is much more difficult to prepare for and anticipate errors. Exceptions can either have their checkboxes ticked or left unchecked. However, errors are never checked for or eliminated. Exceptions are almost always an indication that the programmer has made a mistake. On the other hand, errors might be brought about by a malfunction in the system itself or by the incorrect utilization of a resource. Consequently, handling exceptions should be done at the application level, while handling errors should be done at the system level (only if possible). As soon as you have dealt with an exception, you are certain to return to the normal flow of the application. However, even if a mistake is discovered, the programmer might not be aware of how to deal with it in the first place. Unlike more conventional methods of error management, exceptions make it possible to keep error-handling code distinct from other types of code.

Python comes with a term called finally that is always performed after the try and except blocks have been completed. The final block will always execute after the try block has finished executing normally or after the try block has finished executing owing to an exception.

    # Some Code.... 
    # optional block
    # Handling of exception (if required)
    # execute if no exception
    # Some code .....(always executed)

Python Exception Handling Article Concluded. Over time, we have observed a wide variety of exceptions and seen a wide variety of responses. Assertions and user-defined exceptions were also covered in class.



Register New Account
Shopping cart