Exception Handling in Python with Examples

Tutorial Playlist

Python is one of the most commonly used programming languages in today’s world. This is because Python is simple to write as it provides a wide range of built-in libraries that ease the developer’s job. However, you might encounter some errors while executing the Python programs, which delays the development process. To ensure that Python programs run smoothly, without encountering errors, exception handling comes into place. Python exception handling allows the compiler to ignore errors from a particular section of the code that is already defined by the developer.

In this article, you will learn about exception handling in Python, conflicts that might arise, Python’s built-in exceptions, some user-defined exceptions, and best practices that can be followed.

Table of Contents:

What are Exceptions in Python?

Exceptions are errors that are not in the syntax, but more like operations that might result in error when executed. These types of errors can be handled by instructing the compiler to ignore if that specific error occurs. This is where exception handling in Python comes into play.

Example:

# Python code to check Exceptions

Python

Output:

Traceback (most recent call last):
File " /temp/aaec53c.python", line 3, in
print(num[7])
IndexError: list index out of range

Here, in this code, the compiler returns an IndexError because the developer has requested to print the value of the index that is not in the range.

Some other common exceptions that occur:

  • TypeError: This exception occurs when you want to apply an operation that is of a different type compared to the object.
For example, “abc” + 5, here we are trying to add a string and an integer.
  • ValueError: This exception occurs when we provide an inappropriate value to an operation.
For example, int(“Intellipaat”), here we are trying to convert a string into an integer, which is not allowed.
  • AttributeError: This error occurs when the attributes are incorrectly referenced.
For example,
num = 15
append(20)
This will result in an error as integer datatypes do not have the append attribute.
  • NameError: This error occurs when the variable or method name that is used in an operation is not already defined.
For example, print(num), here the variable num is not already defined.
  • ZeroDivisionError: As the name suggests, this error occurs when you try to divide a number by zero.
For example, num = 45/0, here the ZeroDivisionError occurs.
Become a Certified Python Programmer
Master Python Programming and Start Building Powerful Applications
quiz-icon

Python Built-in Exceptions

There are some built-in exceptions in Python classes that are already defined for generic cases. They are mentioned in the table below:

Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
AttributeError Raised when attribute reference or assignment fails
EOFError Raised when the input() method hits an “end of file” condition (EOF)
FloatingPointError Raised when a floating-point calculation fails
GeneratorExit Raised when a generator is closed (with the close() method)
IndexError Raised when an index of a sequence does not exist
IndentationError Raised when indentation is not correct
KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z, or Delete
LookupError Raised when errors raised cant to be found
MemoryError Raised when a program runs out of memory
NotImplementedError Raised when an abstract method requires an inherited class to override the method
OverflowError Raised when the result of a numeric calculation is too large
RuntimeError Raised when an error occurs that do not belong to any specific exceptions
SyntaxError Raised when a syntax error occurs
SystemError Raised when a system error occurs
TabError Raised when indentation consists of tabs or spaces
UnboundLocalError Raised when a local variable is referenced before assignment
UnicodeError Raised when a Unicode problem occurs
ValueError Raised when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero

Get 100% Hike!

Master Most in Demand Skills Now!

Exception Handling In Python

Python exception handling is the method of writing structured processes to identify and handle exceptions that might disrupt the program execution. These methods of exception-handling stop the program from abrupt termination rather they allow programs to manage such errors gracefully. Python allows the use of techniques like try and except to bypass the block which encounters an error and executes an alternative code block that is passed in the except block. With these techniques, we can also generate error messages or warnings to users, to rectify these errors later.

In Python, exceptions can be handled by using the following methods:

  • Try-except-else clause
  • Try-finally clause
  • Raise clause

Try-except-else Clause

In this technique, the developer identifies a block of code that might generate an error when executed. To handle this error, the developer puts that code in the try block, which shows that the compiler will check for errors in this block, and if an error occurs then the compiler looks for an alternative code. This alternative code is defined using the except block. The compiler executes the code in an except block in case an error is encountered. Further, an else block is provided which executes when the try block doesn’t encounter an error.

Syntax:

try:
Your statements
except Exception_1:
If there is Exception_1 then execute this block- statement
except Exception_2:
If there is Exception_2 then execute this block-statement
else:
if no exception was raised-statement

Now, let us understand this try-except-else technique with an example:

try:
     List = [1, 2, 3, 4, 5]
     value = List[6]
except IndexError:    #Executes this block if IndexError occurs
     print('Error: Index out of range. Please input a valid index')
else:    #Executes this block if no error is encountered
     print(value)

Handling Process of try-except-else Block

Let’s understand what exactly happens in a try-except-else block with the help of the following flowchart:

First, the try block is executed

  • Case 1: If no Python exception occurs, except blocks, are skipped and the else block gets executed
  • Case 2: If a Python exception occurs during the execution of the try block, the rest of the execution is stopped. Then, a matching Python exception handling block is looked for.
    • If found: Execute that exception block, and after the exception in Python is handled, execute the rest of the try block
    • If not found: Stop the whole execution with an error message

Note: Python can handle any number of exceptions.

Try-finally Clause

When a finally clause is used in a try block, then its block of statements is always executed by the Python compiler, whether an exception occurred while the try block was running or not:

  • If no exception occurs, Python runs the try block and the finally block and then continues executing the rest.
  • If an exception in Python occurs during the execution of the try block, Python starts executing the finally block but then propagates the execution to the except block to handle the exception.

Example:

try:
file1 = open("test.txt", "w")
except IOError:
print("Error: File not found")
try:
file1.write("Test is not present")
except IOError:
print("Error: Writing to file failed")
finally:
print("So, let's close the file")
file1.close()

Here, we can notice that the exception block is not executed. This is because the file gets closed after the execution of the final block.

Raise Exceptions in Python

Python allows its users to raise exceptions of their own using the predefined ‘raise’ keyword. Go through the following syntax if you want to raise an error of your own:

Syntax:

raise Exception_name(“Message to User”)

Example:

class RaisingValueError(Exception):
    def __init__(self, data):
        self.data = data

    def __str__(self):
        return repr(self.data)

Total_movie = int(input("Enter the total number of movies you have seen: "))

try:
    Num_of_genres = int(input("Enter the number of genres: "))
    if Num_of_genres < 1:
        raise RaisingValueError("The number of genres can't be less than 1.")
except RaisingValueError as e:
    print("Please try again:", e.data)

Here, in this code, the compiler will raise an error if the number of genres is provided by the user as an input is less than 1.

Data Science and AI: Transforming the Future
Learn How Artificial Intelligence is Revolutionizing Data Science Practices
quiz-icon

Conflicts in Python Exception Handling

Though exception handling in Python is easy to use, you might encounter some conflicts while performing exception handling. These conflicts can arise when there are multiple exceptions in the code, then it might occur that some exceptions get skipped.

For example, if we add a generic exception before a specific exception, then the specific exception will be skipped, i.e. it will never get caught by the compiler.

try: 
     num = int(“Intellipaat”)
except Exception:
     print(“A general exception has occurred.”)
except ValueError:
     print(“Value Error: Trying to convert String to Number.”)

Here, in this code, the ValueError exception is written after the generic Exception, so the compiler will not catch the ValueError exception because the Exception class will cover all the exceptions.

So, if you want the Python compiler to catch both exceptions, then you will have to place the specific exception before the generic exception.

User-defined Exceptions in Python

Programmers can define their own exceptions by creating a new exception class. They need to be derived, indirectly or directly, from the built-in class, Exception. Most built-in exceptions are also derived from the same class.

Python

Output
A New Exception occurred: 6

Best Practices for Exception Handling in Python

Let’s discuss the best practices of exception handling in Python,

  1. Catch only specific exceptions: Always be specific on what type of exception you would like to catch. Avoid using the generic ‘Exception’ class.
  2. Avoid writing empty exceptions: Make sure you define a meaningful exception using the correct exception type.
  3. Use multiple except blocks: If you want to catch multiple exceptions, then you must define separate except blocks for each, to make the code easy to read.
  4. Use finally block: Try to always mention the finally block at the end, as it is used for the cleanup process.
  5. Use logging module: You should consider using the logging module along with exceptions. This is done to keep track of all the exceptions that occur while compilation. Logging helps in making the debugging process easier.

Custom Exception Classes in Python

In addition to handling built-in exceptions, you can create your own custom exception classes to capture application-specific errors more accurately.

Example:

class CustomError(Exception):
    def __init__(self, message):
        super().__init__(message)
try:
     age = int(input("Enter your age: "))
     if age < 0:
         raise CustomError("Age cannot be negative.")
except CustomError as ce:
    print(f"Custom Error: {ce}")
except ValueError:
    print("Invalid input. Please enter a valid number.")
else:
    print("Age entered:", age)
finally:
    print("Exception handling complete.")

Context Managers and the with Statement

Python’s context managers, often used with the with statement, provide a clean way to manage resources and ensure they are properly released without using the finally block explicitly.

try:
    with open("example.txt", "r") as file:
        content = file.read()
       # Perform operations on content
except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print(f"An error occurred: {e}")
else:
    print("File successfully read.")
finally:
    print("Exception handling complete.")

Conclusion

Exception handling in Python is important as it helps in writing more readable and reliable code. By now, you must have gotten an idea of how try, except, else, finally, and raise blocks are used for handling exceptions in Python effectively. Developers can use various built-in exceptions, create exceptions of their own, and follow the best practices to write error-free codes.

This brings us to the end of this module in Python Tutorial. Further, you can also refer to the trending Python coding interview questions prepared by industry experts.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 11th Feb 2025
₹20,007

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.