Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. Common Built-in Exceptions

Common Built-in Exceptions

Python provides many built-in exception classes. Knowing the types of errors helps you write appropriate except blocks. In except blocks, always specify a concrete exception class — avoid catching everything with a bare except or except Exception as a general rule.

Common Built-in Exceptions

Exception ClassWhen It Occurs
ValueErrorThe type is correct but the value is invalid (e.g., int('abc')).
TypeErrorAn operation is applied to a value of an inappropriate type (e.g., 'text' + 1).
KeyErrorA dictionary is accessed with a key that does not exist.
IndexErrorA list is accessed with an index that is out of range.
AttributeErrorAn attribute or method that does not exist on the object is accessed.
FileNotFoundErrorAn attempt is made to open a file that does not exist.
ZeroDivisionErrorAn attempt is made to divide by zero.
NameErrorAn undefined variable is referenced.
ImportErrorA module import fails.
StopIterationAn iterator runs out of items (normally handled automatically).
RecursionErrorThe maximum recursion depth is exceeded.
MemoryErrorThe program runs out of memory.
OverflowErrorThe result of a numeric operation is too large (floats only; ints have arbitrary precision).
NotImplementedErrorRaised intentionally when a method that a subclass should implement has not been implemented.

Sample Code

# ValueError: invalid value
try:
    n = int('abc')
except ValueError as e:
    print(f"ValueError: {e}")   # invalid literal for int() with base 10: 'abc'

# TypeError: incorrect type
try:
    result = 'Age: ' + 25
except TypeError as e:
    print(f"TypeError: {e}")    # can only concatenate str (not "int") to str

# KeyError: key not found in dictionary
user = {'name': 'Alice', 'age': 30}
try:
    email = user['email']
except KeyError as e:
    print(f"KeyError: {e}")     # KeyError: 'email'

# IndexError: index out of range
fruits = ['apple', 'banana', 'cherry']
try:
    print(fruits[10])
except IndexError as e:
    print(f"IndexError: {e}")   # list index out of range

# AttributeError: attribute does not exist
try:
    'hello'.upper_case()    # upper_case() does not exist
except AttributeError as e:
    print(f"AttributeError: {e}")

# FileNotFoundError: file does not exist
try:
    with open('nonexistent_file.txt') as f:
        content = f.read()
except FileNotFoundError as e:
    print(f"File not found: {e.filename}")

# ZeroDivisionError: division by zero
try:
    result = 100 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

# Check exception inheritance
print(issubclass(FileNotFoundError, OSError))   # True
print(issubclass(ZeroDivisionError, ArithmeticError))   # True
print(issubclass(ValueError, Exception))        # True

# Inspect the exception object
try:
    x = int('abc')
except ValueError as e:
    print(type(e).__name__)     # ValueError
    print(str(e))               # error message
    print(e.args)               # tuple of error arguments

Overview

Python's exception classes are organized in a hierarchy. At the top is BaseException, with Exception (for regular program errors), KeyboardInterrupt, SystemExit, and others beneath it. In typical error handling, you deal with subclasses of Exception.

Understanding the exception class hierarchy lets you catch errors at the right level of granularity. For example, FileNotFoundError is a subclass of OSError, so you could catch it with except OSError — but specifying FileNotFoundError directly makes your intent clearer.

Silently ignoring an exception with a bare except and pass is an anti-pattern that makes bugs hard to find. At a minimum, add a log statement or print to record that an error occurred.

If you find any errors or copyright issues, please .