Table of contents
1.
Introduction
2.
What is an Exception?
2.1.
Example
3.
Types of Exceptions
3.1.
1. Built-in Exception: 
3.2.
2. User-Defined Exception: 
4.
What is Exception Handling in Python?
5.
Handling Exceptions with try-except block
5.1.
Syntax:
5.2.
Example:
6.
Handling Exceptions With Try-Except-Else Block
7.
Handling Exceptions With Finally block 
8.
Raising an Exception
8.1.
Example:
9.
Assertion Error
9.1.
Example:
10.
Finally Keyword in Python
10.1.
Example:
11.
Common Exceptions in Python
12.
Advantages of Exception Handling
13.
Disadvantages of Exception Handling
14.
Frequently Asked Questions
14.1.
What is the purpose of exception handling?
14.2.
What is the difference between final, finally, and finalize?
14.3.
What is exception handling?
14.4.
What is finally in Python?
14.5.
What is an error in Python?
14.6.
Which exception catches all exceptions in Python?
15.
Conclusion
Last Updated: Mar 27, 2025
Easy

Exception Handling in Python

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Python exception handling allows programmers to gracefully manage these interruptions by anticipating potential errors and specifying actions to take when such exceptions occur. It ensures robustness and prevents abrupt crashes, enhancing the reliability and usability of Python applications.

During program execution, an exception occurs, interrupting the normal flow of instructions. Python scripts must handle exceptions immediately, or they terminate and quit when an exception occurs. Exceptions are Python objects that represent errors.

Exception Handling in Python

An error in Python can be either a syntax error or an exception. This article explains what Exception Handling is.

What is an Exception?

The programmer can handle an exception if it occurs at runtime. Python represents exceptions as classes.

Errors can be categorized into three types:

  • Compile-time error: Software can contain errors such as missing semicolons, incorrectly spelled keywords, or errors in syntax. These errors are called syntactical errors or compile-time errors.
  • Logical Error: A problem with a program that causes it to run inaccurately without causing the program to terminate abnormally.
  • Runtime Error: A runtime error happens when a program you're using or writing crashes or produces a wrong output. The program may not be able to function correctly.

 

In other words, as a developer, you need to address all these errors and prevent what a user can do wrong to cause the application to crash. The user is not only responsible for these errors but also the server, internet connection, database connection, etc. Exception Handling in Python means that the execution should not be halted even if you encounter an error or Exception.

Example

x=8
y=0
print(x/y)
print(“end”)


Output:


 

In this program, we can see that x/y = 8/0 gives ZeroDivisionError, but this won't be easy to understand by a normal user.

Another problem with your execution is that you stopped it in between, so the "end" didn't appear on the screen. 
 

To solve this problem, we can use a try-except block like below:

x=8
y=0
try:    //try block
    print(x/y)
except Exception:    //except block
    print("Given number cannot be divided by Zero")    //Write the message for the user
print("end")


Output:

A try-except block allows you to avoid the termination of the code in between, and it also clarifies what the exact error is to the user.

Types of Exceptions

There are two types of Exceptions:

1. Built-in Exception: 

All built-in BaseException classes are based on this class already present in Python.
 

2. User-Defined Exception: 

An Exception created by a programmer is known as a user-defined exception.

What is Exception Handling in Python?

Exception handling in Python is a mechanism to handle runtime errors gracefully. It prevents program crashes by catching and managing exceptions using try, except, finally, and raise blocks, ensuring smooth and controlled execution.

Handling Exceptions with try-except block

To solve the problem of Exceptions, you can use a try-except block in which:

  • try: Exceptions raised in try will jump straight into the except Block.
  • except: Exceptions raised in try will only be handled by the except Block. Even if a try block contains only a pass statement, an except block is still required.
     

Syntax:

try:
    //Statements
except Exception:
    //Statements

 

Example:

Here is a program for opening a text file named newfile.txt.

try:
    with open('newfile.txt') as file:
        readfile= file.read()
except:
    print ("newfile.txt does not exist.")


Output:

Handling Exceptions With Try-Except-Else Block

If there is no exception, then the else block will be executed. After the try Block, the else blocks are executed.

Example:

try:
    f = open('newfile.txt')
except IOError:
    print("newfile.txt doesn't exist")
else:
    print("File exists!")


If newfile.txt exists and opens correctly, an exception is not raised, and the else clause will be executed. If newfile.txt does not exist, the else clause will not be executed.

Output:

Handling Exceptions With Finally block 

This is another example of exception handling. We can include a final block when we handle exceptions with the try and except Block. The finally Block is used to close file resources, close database connections, or display a message at the end of the program execution.

Example:

try:
    f = open('newfile.txt')
except IOError:
    print("newfile.txt doesn't exist")
else:
    print("File exists!")
finally:
    print("This statement will always gets executed.")


Output:

You can practice by yourself with the help of online python compiler.

Raising an Exception

Raising an exception is possible using raise. By using the raise statement, the programmer can force a specific exception to occur. Only one argument is passed to raise, indicating the exception to raise.

Example:

number = 12
if number < 20:
    raise Exception('number should be greater than 20') 


Output:

Assertion Error

In Python, an assert statement can be used to validate any condition within a program. The program will continue if the assertion is true. When the condition is False, we get the AssertionError. This disrupts the flow of the program.

Example:

try:
    assert "Ninja2022" == "Ninja2021" 
except AssertionError:
    print ("Some issue has occurred.")


Output:


 

Some points to remember: 

  • It is possible to write several except blocks for a single try block.
  • The try block can be written without ant except for blocks, but it has no meaning.
  • To handle multiple exceptions, we can write multiple except blocks.
  • It is impossible to write an except block without a try block.
  • It is optional to include an Else and Finally block.
  • Whether an exception occurs or not, the finally block is always executed.

Finally Keyword in Python

In Python, the finally keyword is used in try...except...finally blocks to ensure that a specific block of code runs regardless of whether an exception is raised or not. The code within finally will always execute, even if the try block completes successfully or if an exception occurs in the try block or is caught by except. This is especially useful for cleanup tasks, such as closing files or releasing resources, to prevent resource leaks.

Example:

try:
    file = open("example.txt", "r")
    # Read or process file
except FileNotFoundError:
    print("File not found.")
finally:
    file.close()  # Ensures the file is closed, no matter what

Common Exceptions in Python

Python has several built-in exceptions that occur during program execution. Below are some common exceptions along with their descriptions:

Exception NameDescription
ZeroDivisionErrorRaised when a number is divided by zero.
TypeErrorOccurs when an operation is performed on an inappropriate data type.
ValueErrorRaised when a function receives an argument of the correct type but an invalid value.
IndexErrorOccurs when accessing an invalid index in a list or tuple.
KeyErrorRaised when a dictionary key is not found.
AttributeErrorOccurs when an invalid attribute is accessed on an object.
FileNotFoundErrorRaised when trying to open a file that does not exist.
ImportErrorOccurs when an imported module cannot be found or loaded.
NameErrorRaised when a variable or function is not defined.
IndentationErrorOccurs due to incorrect indentation in the code.

Advantages of Exception Handling

  • Improves Program Robustness: Allows the program to handle errors gracefully and continue executing, rather than terminating abruptly.
  • Simplifies Error Resolution: Enables targeted debugging by catching specific errors and managing them systematically.
  • Enhances Code Readability: Separates normal code from error-handling code, making it easier to read and maintain.
  • Enables Resource Management: Ensures resources like files, databases, or network connections are properly managed, even if errors occur.
  • Supports Cleaner Code Flow: Avoids unnecessary conditional checks by managing exceptions directly, creating a smoother control flow.

Disadvantages of Exception Handling

  • Potential for Overuse: Overusing exception handling can make code complex and harder to debug, especially when handling non-critical exceptions.
  • Performance Overhead: Exception handling can introduce performance overhead, especially when exceptions are raised and caught frequently.
  • Can Mask Programming Errors: Improper use of broad except clauses may hide actual bugs in the code, leading to unexpected behavior.
  • Increases Code Complexity: Complex exception handling structures can reduce readability and increase the maintenance effort required.

Frequently Asked Questions

What is the purpose of exception handling?

Maintaining the normal flow of an application is the key advantage of exception handling. We need to handle exceptions because they disrupt the normal flow of an application.

What is the difference between final, finally, and finalize?

Finally is the Block in Exception Handling, which gets executed every time, finalize is a method of the object class, and Final is an access modifier.

What is exception handling?

Exception handling in Python is implemented using try, except, finally, and raise blocks, allowing programs to handle runtime errors and prevent unexpected crashes.

What is finally in Python?

The finally block in Python executes code regardless of whether an exception occurs, ensuring cleanup actions like closing files or releasing resources.

What is an error in Python?

An error in Python is an issue in code execution, categorized into syntax errors (invalid syntax) and exceptions (runtime errors causing program interruption).

Which exception catches all exceptions in Python?

The Exception class catches most exceptions, but BaseException (or except: without specifying an exception) can catch all exceptions, including system-exiting ones.

Conclusion

Exception handling in Python is essential for writing robust and error-free programs. By using try, except, finally, and raise, developers can effectively handle runtime errors, prevent crashes, and ensure smooth execution. Understanding common exceptions helps in debugging and improving code reliability.

Recommended Readings:

Live masterclass