Exception Handling in Python

By Pankaj Chouhan | Codes with Pankaj

Errors are a normal part of programming. Even experienced developers face them daily. The good news? Python gives us powerful tools to handle these errors gracefully so our programs don’t crash unexpectedly.

In this blog, you will learn exception handling in Python step by step with easy-to-understand examples.

What is an Exception?

An exception is an error that occurs while a program is running (at runtime). If not handled, it stops the program immediately.

Common Example:

a = 10
b = 0
result = a / b
print(result)

Output:

ZeroDivisionError: division by zero

The program crashes. This is not a good user experience.

The try and except Block

The basic way to handle exceptions is using try and except.

try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))
    result = a / b
    print("Result:", result)

except:
    print("Something went wrong! Please enter valid numbers.")

How it works:

  • Code inside try is executed.
  • If an error occurs, the program jumps to the except block.
  • If no error occurs, except is skipped.

Handling Specific Exceptions (Recommended)

It’s better to catch specific errors instead of a general except.

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print("Result:", result)

except ZeroDivisionError:
    print("Error: You cannot divide by zero!")

except ValueError:
    print("Error: Please enter a valid number, not text!")

Some Common Exceptions:

  • ZeroDivisionError
  • ValueError
  • TypeError
  • FileNotFoundError
  • IndexError
  • KeyError

else and finally Blocks

try:
    file = open("data.txt", "r")
    content = file.read()
    print(content)

except FileNotFoundError:
    print("File not found!")

else:
    print("File read successfully!")   # Runs only if no exception

finally:
    print("This will always run - Cleanup code here")
    # Close file if it was opened

  • else: Executes only when no exception occurs.
  • finally: Always executes (perfect for closing files, database connections, etc.).

Example: Reading a File Safely

def read_file(filename):
    try:
        with open(filename, "r") as file:
            data = file.read()
            return data
    except FileNotFoundError:
        return "Error: File not found. Please check the filename."
    except PermissionError:
        return "Error: You don't have permission to read this file."
    except Exception as e:
        return f"Unexpected error: {e}"

print(read_file("students.csv"))

Raising Your Own Exception

def check_age(age):
    if age < 18:
        raise ValueError("Age must be 18 or above to register!")
    print("Registration successful!")

try:
    check_age(16)
except ValueError as e:
    print("Error:", e)

Best Practices for Exception Handling

  1. Always catch specific exceptions first.
  2. Use finally for cleanup tasks.
  3. Keep error messages user-friendly.
  4. Avoid using a bare except: in production code.
  5. Log errors (using the logging module) for debugging.

Conclusion

Exception handling makes your Python programs more robust, reliable, and user-friendly. Instead of crashing, your application can show helpful messages and continue running.

Mastering try, except, else, and finally is an essential skill for every Python developer.

Practice Exercise:
Create a simple calculator that handles division by zero and invalid input errors.

Codes with Pankaj – Making Coding Simple and Practical.

Scroll to Top