Python Exception Handling

Python 10 min min read Updated: Mar 09, 2026 Intermediate
Python Exception Handling
Intermediate Topic 7 of 10

Exception Handling in Python

While running a Python program, errors may occur due to invalid input, incorrect operations, or unexpected situations. If these errors are not handled properly, the program may crash and stop execution. To avoid such situations, Python provides a mechanism called exception handling.

Exception handling allows developers to detect errors during runtime and manage them gracefully without terminating the entire program.

What is an Exception?

An exception is an error that occurs during the execution of a program. When Python encounters an error, it raises an exception and stops the normal flow of the program.

For example, dividing a number by zero produces an error.

python num = 10 print(num / 0)

This will produce a ZeroDivisionError.

Why Exception Handling is Important

  • Prevents programs from crashing
  • Helps manage unexpected errors
  • Improves user experience
  • Makes programs more reliable and stable

The try and except Block

The try block contains code that may cause an exception, while the except block handles the error.

python try: num = int(input("Enter a number: ")) print(10 / num) except: print("An error occurred")

If an error occurs inside the try block, Python will execute the except block instead of stopping the program.

Handling Specific Exceptions

It is better practice to handle specific exceptions instead of using a general exception handler.

python try: num = int(input("Enter a number: ")) result = 10 / num print(result) except ZeroDivisionError: print("Cannot divide by zero") except ValueError: print("Invalid input")

This example handles different types of errors separately.

The else Block

The else block executes if no exception occurs in the try block.

python try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Division by zero is not allowed") else: print("Result:", result)

The else block ensures that the result is printed only when the operation is successful.

The finally Block

The finally block always executes regardless of whether an exception occurs or not.

python try: file = open("data.txt", "r") content = file.read() except FileNotFoundError: print("File not found") finally: print("Execution completed")

The finally block is commonly used for cleanup operations such as closing files or releasing resources.

Raising Exceptions

Python also allows developers to manually raise exceptions using the raise keyword.

python age = int(input("Enter your age: ")) if age < 0: raise ValueError("Age cannot be negative")

This ensures that invalid data is detected immediately.

Common Python Exceptions

Exception Description
ZeroDivisionError Occurs when dividing by zero
ValueError Occurs when invalid value is provided
TypeError Occurs when incompatible data types are used
IndexError Occurs when accessing an invalid index
FileNotFoundError Occurs when a file cannot be found

Real-World Example

python try: username = input("Enter username: ") password = input("Enter password: ") if username == "" or password == "": raise ValueError("Fields cannot be empty") print("Login successful") except ValueError as e: print("Error:", e)

This example validates user input and prevents empty values.

Best Practices for Exception Handling

  • Handle specific exceptions instead of using a generic exception.
  • Avoid placing too much code inside the try block.
  • Use finally for cleanup tasks.
  • Provide meaningful error messages.

Conclusion

Exception handling is an essential feature in Python that allows developers to manage runtime errors effectively. By using try, except, else, and finally, programmers can build stable and reliable applications that continue running even when unexpected errors occur.

In the next tutorial, we will explore Modules & Packages in Python and learn how Python organizes reusable code.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators