Common Python Exceptions: A Practical Guide with Examples

‘s exception system helps you deal with problems that happen while a program is running. Instead of allowing your program to stop unexpectedly, you can detect certain errors and respond to them in a controlled way.

For beginners, learning common exceptions is important because error messages are a normal part of programming. Once you understand what an exception means, you can usually find the problem much faster and decide how to handle it.

What Are Exceptions?

An exception is a problem that occurs while Python is executing your program.

For example, Python cannot divide a number by zero:

result = 10 / 0

When Python reaches this line, it raises a ZeroDivisionError. If you do not handle the exception, the program stops and Python displays an error message called a traceback.

You can think of an exception as Python telling you that something went wrong and it cannot continue that operation normally.

Why Do We Handle Exceptions?

Without exception handling, a small problem can stop an entire program.

For example, imagine a program asking the user to enter their age:

age = int(input("Enter your age: "))

If the user enters abc instead of a number, Python cannot convert the text into an integer and raises a ValueError.

We can handle the problem and show a useful message instead:

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Please enter a valid number.")

The purpose of exception handling is to deal with expected problems safely instead of allowing them to stop the program unexpectedly.

Basic try / except Structure

The most common way to handle an exception is with try and except.

try:
    # Code that might cause an exception
except SomeException:
    # Code that handles the exception

The try block contains code that might fail. The except block tells Python what to do when a particular exception occurs.

For example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero.")

Python starts by running the code inside try. When it reaches 10 / 0, it raises ZeroDivisionError. Python then looks for a matching except block and runs it.

Quick Reference Table

Exception When It Happens Simple Example
ValueError A value is not suitable for the operation. int("abc")
TypeError An operation is used with an inappropriate data type. "5" + 5
NameError Python cannot find a variable or other name. print(username)
IndexError A list or sequence position does not exist. names[10]
KeyError A dictionary key does not exist. user["email"]
FileNotFoundError The requested file or directory cannot be found. open("abc.txt")
ZeroDivisionError A number is divided or modulo-divided by zero. 10 / 0
PermissionError The program does not have permission to access a resource. Opening a protected file
KeyboardInterrupt The user manually interrupts the program. Ctrl+C
EOFError Python reaches the end of an input stream unexpectedly. input()
OSError An operating-system operation fails. os.remove()
AttributeError An object does not have the requested attribute or method. "hello".append()

Detailed Look at Common Exceptions

1. ValueError

ValueError is raised when a function receives a value that is not suitable for the operation, even though the type of the value is acceptable.

A common example is converting text into an integer. A string can be passed to int(), but the string must contain a valid number.

try:
    number = int("hello")
except ValueError:
    print("Cannot convert that text into a number.")

Here, "hello" is a string, but it does not represent a valid integer. A value such as "25" would work:

number = int("25")
print(number)

A useful way to remember ValueError is: the type is acceptable, but the value is not.

2. TypeError

TypeError is raised when an operation is used with an inappropriate data type.

For example, Python cannot directly add a string and an integer:

try:
    result = "5" + 5
except TypeError:
    print("You cannot add a string and an integer directly.")

The problem is that "5" is a string while 5 is an integer. Python does not automatically decide how these two different types should be combined.

You can convert the number to a string when your goal is to join the text:

result = "5" + str(5)
print(result)

Here, both values are strings, so the operation is valid.

3. NameError

NameError is raised when Python cannot find a name that you are trying to use.

This commonly happens when a variable has not been created or its name has been misspelled.

try:
    print(username)
except NameError:
    print("The variable 'username' has not been defined.")

There is no variable named username before the print() statement, so Python does not know what it refers to.

Defining the variable first solves the problem:

username = "Alice"
print(username)

When you see a NameError, check the spelling and make sure the variable or function was defined before you used it.

4. IndexError

IndexError is raised when you try to access an item at a position that does not exist in a list or another sequence.

Python list indexes start at 0. A list containing three items therefore has the indexes 0, 1, and 2.

names = ["Alice", "Bob", "Charlie"]
try:
    print(names[10])
except IndexError:
    print("That index does not exist in the list.")

The list contains only three items, so index 10 is outside the valid range.

To access the last item, you can also use a negative index:

names = ["Alice", "Bob", "Charlie"]
print(names[-1])

This prints Charlie because -1 refers to the last item.

5. KeyError

KeyError is raised when you try to access a dictionary using a key that does not exist.

Dictionaries store information as key-value pairs. If the requested key is missing, Python cannot return a value for it.

user = {
    "name": "Alice"
}
try:
    print(user["email"])
except KeyError:
    print("The key 'email' does not exist.")

The dictionary contains name, but there is no email key.

You can avoid this problem in some situations by using the get() method:

user = {
    "name": "Alice"
}
email = user.get("email")
print(email)

If the key is missing, get() returns None instead of raising a KeyError.

6. FileNotFoundError

FileNotFoundError is raised when Python tries to open or access a file or directory that cannot be found.

This can happen when the file does not exist, the filename is incorrect, or the path is wrong.

try:
    with open("missing_file.txt") as file:
        content = file.read()
except FileNotFoundError:
    print("The file was not found.")

If missing_file.txt is not available at the expected location, Python raises the exception.

Checking the filename and path carefully can prevent this error.

7. ZeroDivisionError

ZeroDivisionError is raised when you try to divide a number by zero or perform a modulo operation using zero.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed.")

Python does not allow division by zero because the result is mathematically undefined.

You can also check the value before performing the calculation:

number = 0
if number != 0:
    result = 10 / number
else:
    print("The number cannot be zero.")

Using a simple check like this can be useful when zero is an expected possibility.

8. PermissionError

PermissionError is raised when your program does not have enough permission to perform an operation.

Operating systems protect files and other resources, so a normal user may not be allowed to read, modify, delete, or access certain locations.

try:
    with open("/root/secret.txt") as file:
        print(file.read())
except PermissionError:
    print("You do not have permission to access this file.")

The exact result depends on your operating system, account permissions, and the permissions assigned to the file.

A file can therefore exist and still produce a PermissionError because the current user is not allowed to access it.

9. KeyboardInterrupt

KeyboardInterrupt occurs when the user manually interrupts a running Python program. This usually happens by pressing Ctrl+C in a terminal.

This can be useful when a program is running for a long time or contains a loop that does not normally stop by itself.

try:
    while True:
        print("Program is running...")
except KeyboardInterrupt:
    print("\nProgram interrupted by the user.")

When you press Ctrl+C, Python raises KeyboardInterrupt and the except block handles it.

10. EOFError

EOFError can occur when Python is waiting for input but reaches the end of the input stream before receiving the expected data.

try:
    data = input("Enter something: ")
except EOFError:
    print("No input was received.")

This is more common when input is redirected from another program, file, or input stream.

On Unix-like systems, Ctrl+D can signal the end of input. On Windows, Ctrl+Z followed by Enter is commonly used.

11. OSError

OSError represents many problems reported by the operating system while Python is performing an operating-system operation.

It can occur during file operations, directory operations, and other interactions with the system.

import os
try:
    os.remove("non_existent_file.txt")
except OSError as error:
    print(f"Operating system error: {error}")

For example, the file may not exist, the path may be invalid, or the operating system may prevent the requested operation.

Several more specific exceptions, including FileNotFoundError and PermissionError, are related to OSError.

12. AttributeError

AttributeError is raised when you try to access an attribute or method that an object does not provide.

Different Python objects have different methods. A list has an append() method, but a string does not.

try:
    "hello".append("!")
except AttributeError:
    print("Strings do not have an 'append' method.")

The same operation works with a list:

items = ["hello"]
items.append("!")
print(items)

When you see an AttributeError, check the type of the object and make sure the attribute or method you are trying to use actually belongs to it.

Handling More Than One Exception

Different problems can occur in the same piece of code. You can use multiple except blocks to handle them separately.

try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ValueError:
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("The number cannot be zero.")

If the user enters hello, Python raises ValueError. If the user enters 0, Python raises ZeroDivisionError.

Handling each one separately allows you to provide a more useful message.

The else Block

The else block runs only when no exception occurs in the try block.

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("That is not a valid number.")
else:
    print(f"You entered {number}.")

In this example, the else block runs only when the conversion to an integer succeeds.

This is useful when you want to keep successful code separate from error-handling code.

The finally Block

The finally block runs whether an exception occurs or not.

try:
    print("Trying to perform an operation.")
except Exception:
    print("Something went wrong.")
finally:
    print("This code always runs.")

This makes finally useful for cleanup tasks that should happen regardless of the result of the operation.

For example:

try:
    file = open("example.txt")
    content = file.read()
finally:
    file.close()

For normal file handling, the with open(...) syntax is usually preferred because Python automatically closes the file when the block finishes.

ValueError vs TypeError

These two exceptions are often confusing for beginners.

ValueError means that the type of the value is acceptable, but the value itself is not suitable:

int("abc")

The argument is a string, but "abc" cannot be converted into an integer.

TypeError means that the type itself is not appropriate for the operation:

"5" + 5

Here, Python is being asked to add a string and an integer directly.

A simple way to remember the difference is:

  • ValueError — the value is wrong.
  • TypeError — the type is wrong.

What Is a Traceback?

When an exception is not handled, Python normally displays a traceback.

A traceback shows useful information about where the problem occurred and which exception was raised.

numbers = [10, 20, 30]
print(numbers[10])

You may see an error similar to:

IndexError: list index out of range

The traceback helps you locate the line that caused the problem and understand what Python was trying to do when the exception occurred.

Best Practices for Handling Exceptions

  • Catch specific exceptions. Use except ValueError when you expect a ValueError instead of using a broad except:.
  • Show useful messages. Explain the problem clearly so the user knows what went wrong.
  • Do not silently ignore errors. An empty except block can make debugging much more difficult.
  • Use else for successful operations. It keeps code that depends on success separate from error handling.
  • Use finally for cleanup. It is useful when a task must be performed regardless of whether an exception occurred.
  • Use normal checks when appropriate. Sometimes an if statement is clearer than deliberately causing and catching an exception.

A Simple Real-World Example

The following example combines several ideas from this lesson:

try:
    age = int(input("Enter your age: "))

    if age < 0:
        raise ValueError("Age cannot be negative.")

except ValueError as error:
    print(f"Invalid input: {error}")

else:
    print(f"Your age is {age}.")

finally:
    print("Program finished.")

The program first asks for an age and tries to convert the input into an integer. If the user enters something that is not a valid number, ValueError is raised.

The program also checks whether the age is negative. In that case, it creates a ValueError itself using raise.

When everything is valid, the else block displays the age. The finally block runs at the end regardless of whether an exception occurred.

Conclusion

Exceptions are Python’s way of reporting problems that occur while a program is running. Understanding common exceptions makes it easier to read error messages, find problems in your code, and handle expected situations properly.

The most important exceptions to remember at the beginning are:

  • ValueError — the value is not suitable for the operation.
  • TypeError — the data type is not appropriate.
  • NameError — Python cannot find the name you used.
  • IndexError — the requested list position does not exist.
  • KeyError — the requested dictionary key does not exist.
  • FileNotFoundError — the requested file cannot be found.
  • ZeroDivisionError — you tried to divide by zero.
  • PermissionError — the program does not have permission to perform the operation.
  • AttributeError — the object does not provide the requested attribute or method.

Once you become familiar with these exceptions, Python tracebacks will be much easier to understand. You can then use try, except, else, and finally to make your programs more reliable and easier to use.

Happy coding!

Tags :

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

BACK TO TOP