Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Types of Exceptions

Python Types of Exception - Complete Guide

Learn about the different types of exceptions in Python including built-in exceptions.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Understanding Exception Types
  • Built-in Exceptions Overview
  • SyntaxError
  • TypeError
  • ValueError
  • IndexError
  • KeyError
  • ZeroDivisionError
  • FileNotFoundError
  • AttributeError
  • NameError
  • Exception Hierarchy
  • Common Mistakes
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • Built-in exception types — the most common exceptions
  • SyntaxError — when the code structure is wrong
  • TypeError — when an operation is applied to the wrong type
  • ValueError — when a function receives the right type but wrong value
  • IndexError — when accessing an invalid index
  • KeyError — when accessing an invalid dictionary key
  • ZeroDivisionError — when dividing by zero
  • FileNotFoundError — when a file is not found
  • AttributeError — when accessing a non-existent attribute
  • NameError — when a variable is not defined
  • Exception hierarchy — how exceptions are organized

Understanding Exception Types

Python has many built-in exception types. Each type represents a specific kind of error that can occur in your code. Understanding these types helps you write better error-handling code.

The most common exception types are:

  • SyntaxError — invalid syntax
  • TypeError — operation on wrong type
  • ValueError — right type, wrong value
  • IndexError — index out of range
  • KeyError — key not found in dictionary
  • ZeroDivisionError — division by zero
  • FileNotFoundError — file doesn't exist
  • AttributeError — attribute not found
  • NameError — variable not defined

💡 Key concept: Knowing the type of exception helps you handle it correctly. Each exception type gives you specific information about what went wrong.

Built-in Exceptions Overview

1

Common Built-in Exceptions

Python provides a wide range of built-in exceptions. Here are the most commonly encountered ones:

# Overview of common exceptions

# 1. SyntaxError — invalid syntax
# print("Hello"  # Missing closing parenthesis

# 2. TypeError — wrong type
# "5" + 5  # Can't add string and integer

# 3. ValueError — right type, wrong value
# int("hello")  # Can't convert "hello" to integer

# 4. IndexError — index out of range
# [1, 2, 3][5]  # Index 5 doesn't exist

# 5. KeyError — key not found
# {"a": 1}["b"]  # Key 'b' doesn't exist

# 6. ZeroDivisionError — division by zero
# 10 / 0

# 7. FileNotFoundError — file not found
# open("nonexistent.txt")

# 8. AttributeError — attribute not found
# "string".non_existent_method()

# 9. NameError — variable not defined
# print(undefined_variable)

Characteristics:

  • Each exception type has a specific meaning
  • They are organized in a hierarchy
  • All exceptions inherit from BaseException
  • You can catch specific types or all exceptions

Quick Check: What is the base class for all exceptions? (Answer: BaseException)

SyntaxError

2

Invalid Syntax

A SyntaxError occurs when the Python interpreter encounters code that violates the language's syntax rules. This is the most common error for beginners.

# Common SyntaxError examples

# Missing colon
# if x > 5  # SyntaxError: expected ':'

# Missing closing parenthesis
# print("Hello"  # SyntaxError: unexpected EOF

# Missing closing bracket
# my_list = [1, 2, 3  # SyntaxError: expected ']'

# Using a reserved keyword as a variable
# class = "student"  # SyntaxError: invalid syntax

# Incorrect indentation
# if True:
# print("Hello")  # IndentationError

# Missing operator
# result = 5  3  # SyntaxError: invalid syntax

Characteristics:

  • Occurs at compile time
  • Cannot be handled with try-except
  • Prevents the program from running
  • Usually easy to fix

Quick Check: Can SyntaxError be handled with try-except? (Answer: No — it's a compile-time error)

TypeError

3

Wrong Type

A TypeError occurs when an operation is applied to an object of an inappropriate type. This is one of the most common runtime errors.

# Common TypeError examples

# Adding string and integer
# "5" + 5  # TypeError: can only concatenate str (not "int") to str

# Calling a non-callable object
# my_list = [1, 2, 3]
# my_list()  # TypeError: 'list' object is not callable

# Passing wrong number of arguments
# def greet(name):
#     return f"Hello, {name}"
# greet()  # TypeError: greet() missing 1 required positional argument

# Using an object that doesn't support iteration
# for i in 123:  # TypeError: 'int' object is not iterable
#     print(i)

# Accessing an index on a non-sequence
# my_dict = {"a": 1, "b": 2}
# my_dict[0]  # TypeError: 'dict' object is not subscriptable (when using index)

How to fix:

  • Check the data types you're working with
  • Use type() to verify types
  • Convert types when needed: str(), int(), etc.
  • Check function signatures for correct arguments

Quick Check: What causes a TypeError? (Answer: Using the wrong data type for an operation)

ValueError

4

Right Type, Wrong Value

A ValueError occurs when a function receives the correct type of argument but an inappropriate value. The type is right, but the value doesn't make sense.

# Common ValueError examples

# Converting invalid string to integer
# int("hello")  # ValueError: invalid literal for int() with base 10

# Converting invalid string to float
# float("abc")  # ValueError: could not convert string to float

# Finding a value that doesn't exist
# my_list = [1, 2, 3]
# my_list.index(5)  # ValueError: 5 is not in list

# Removing a value that doesn't exist
# my_list = [1, 2, 3]
# my_list.remove(5)  # ValueError: list.remove(x): x not in list

# Using an invalid format specifier
# "{:.2f}".format("string")  # ValueError: Unknown format code 'f' for object of type 'str'

How to fix:

  • Check the value before using it
  • Use try-except to handle invalid values
  • Use str.isdigit() to check if a string is numeric
  • Check if a value exists before using it

Quick Check: What is the difference between TypeError and ValueError? (Answer: TypeError is wrong type; ValueError is right type but wrong value)

IndexError

5

Index Out of Range

An IndexError occurs when you try to access an index that doesn't exist in a sequence (list, tuple, string, etc.). The index is either too high or negative beyond the length.

# Common IndexError examples

# Accessing an index that doesn't exist
# my_list = [1, 2, 3]
# print(my_list[5])  # IndexError: list index out of range

# Accessing a negative index that's too low
# my_list = [1, 2, 3]
# print(my_list[-10])  # IndexError: list index out of range

# Accessing index in an empty list
# empty = []
# print(empty[0])  # IndexError: list index out of range

# Accessing index beyond length in a loop
# my_list = [1, 2, 3]
# for i in range(5):
#     print(my_list[i])  # IndexError when i == 3

How to fix:

  • Check the length using len()
  • Use if index < len(list) before accessing
  • Use try-except to handle out-of-range errors
  • In loops, use range(len(list)) correctly

Quick Check: When does IndexError occur? (Answer: When accessing an index that doesn't exist)

KeyError

6

Key Not Found in Dictionary

A KeyError occurs when you try to access a dictionary key that doesn't exist. This is a very common error when working with dictionaries.

# Common KeyError examples

# Accessing a non-existent key
# my_dict = {"a": 1, "b": 2, "c": 3}
# print(my_dict["d"])  # KeyError: 'd'

# Using get() to avoid KeyError
# value = my_dict.get("d", "Not found")  # Returns "Not found"

# Using in operator to check
# if "d" in my_dict:
#     print(my_dict["d"])
# else:
#     print("Key not found")

# Accessing nested dictionary key
# user = {"name": "Alice", "address": {"city": "NYC"}}
# print(user["address"]["zip"])  # KeyError: 'zip'

# Accessing a key in a loop
# for key in ["a", "b", "d"]:
#     print(my_dict[key])  # KeyError when key is 'd'

How to fix:

  • Use dict.get(key, default) for safe access
  • Use if key in dict: before accessing
  • Use try-except to handle missing keys
  • Use defaultdict from collections module

Quick Check: What is the safest way to access a dictionary key? (Answer: Use dict.get(key, default))

ZeroDivisionError

7

Division by Zero

A ZeroDivisionError occurs when you try to divide a number by zero. This is a mathematical error that can happen in many situations.

# Common ZeroDivisionError examples

# Simple division by zero
# result = 10 / 0  # ZeroDivisionError: division by zero

# Floor division by zero
# result = 10 // 0  # ZeroDivisionError: integer division or modulo by zero

# Modulo by zero
# result = 10 % 0  # ZeroDivisionError: integer division or modulo by zero

# In a loop
# numbers = [1, 2, 0, 3]
# for num in numbers:
#     result = 10 / num  # ZeroDivisionError when num is 0

# Using variables
# divisor = 0
# result = 10 / divisor  # ZeroDivisionError

How to fix:

  • Check if the divisor is 0 before dividing
  • Use try-except to handle division by zero
  • For lists, filter out zeros before operations
  • Use if divisor != 0: before division

Quick Check: What exception is raised when dividing by zero? (Answer: ZeroDivisionError)

FileNotFoundError

8

File Does Not Exist

A FileNotFoundError occurs when you try to open a file that doesn't exist on the system. This is common when working with file I/O operations.

# Common FileNotFoundError examples

# Opening a non-existent file
# try:
#     with open("nonexistent.txt", "r") as file:
#         content = file.read()
# except FileNotFoundError:
#     print("File not found!")

# Using os.path.exists() to check
# import os
# filename = "nonexistent.txt"
# if os.path.exists(filename):
#     with open(filename, "r") as file:
#         content = file.read()
# else:
#     print(f"File '{filename}' does not exist")

# Using try-except with specific error handling
# try:
#     with open("data.txt", "r") as file:
#         content = file.read()
# except FileNotFoundError as e:
#     print(f"Error: {e}")

How to fix:

  • Check if the file exists using os.path.exists()
  • Use try-except to handle missing files
  • Create the file if it doesn't exist
  • Use relative or absolute paths correctly

Quick Check: What exception is raised when opening a non-existent file? (Answer: FileNotFoundError)

AttributeError

9

Attribute Not Found

An AttributeError occurs when you try to access an attribute or method that doesn't exist for a particular object. This is common when working with objects and modules.

# Common AttributeError examples

# Calling a non-existent method
# my_list = [1, 2, 3]
# my_list.uppercase()  # AttributeError: 'list' object has no attribute 'uppercase'

# Accessing a non-existent attribute
# my_str = "hello"
# print(my_str.upper)  # AttributeError: 'str' object has no attribute 'upper' (without parentheses)

# Using the wrong method name
# my_dict = {"a": 1, "b": 2}
# my_dict.gets("a")  # AttributeError: 'dict' object has no attribute 'gets'

# Accessing an attribute on None
# data = None
# data.append(1)  # AttributeError: 'NoneType' object has no attribute 'append'

# Checking if an attribute exists
# if hasattr(my_str, "upper"):
#     print(my_str.upper())  # Works

How to fix:

  • Check the spelling of methods and attributes
  • Use hasattr() to check if an attribute exists
  • Use dir() to see available attributes
  • Make sure objects are not None

Quick Check: What is the most common cause of AttributeError? (Answer: Using a non-existent method or attribute)

NameError

10

Variable Not Defined

A NameError occurs when you try to use a variable, function, or module that hasn't been defined yet. This is a very common error for beginners.

# Common NameError examples

# Using a variable before defining it
# print(my_variable)  # NameError: name 'my_variable' is not defined

# Misspelling a variable name
# name = "Alice"
# print(nam)  # NameError: name 'nam' is not defined

# Using a function before defining it
# greet()  # NameError: name 'greet' is not defined
# def greet():
#     print("Hello")

# Using an undefined function
# print(len(123))  # NameError: name 'len' is not defined (if len is not imported)

# Using a variable in a different scope
# def my_function():
#     x = 10
# print(x)  # NameError: name 'x' is not defined

How to fix:

  • Check the spelling of variable names
  • Make sure variables are defined before use
  • Check scope — variables inside functions are not accessible outside
  • Import modules before using them

Quick Check: What causes a NameError? (Answer: Using a variable or function that hasn't been defined)

Exception Hierarchy

11

How Exceptions Are Organized

Python exceptions are organized in a hierarchy. All exceptions inherit from BaseException. Understanding this hierarchy helps you catch exceptions at the right level.

# Exception Hierarchy (simplified)

# BaseException
# ├── SystemExit
# ├── KeyboardInterrupt
# ├── Exception (most exceptions inherit from this)
# │   ├── ArithmeticError
# │   │   ├── ZeroDivisionError
# │   │   ├── OverflowError
# │   │   └── FloatingPointError
# │   ├── AttributeError
# │   ├── EOFError
# │   ├── IndexError
# │   ├── KeyError
# │   ├── NameError
# │   ├── TypeError
# │   ├── ValueError
# │   ├── IOError
# │   │   └── FileNotFoundError
# │   └── StopIteration
# └── GeneratorExit

# Example: Catching multiple exceptions
# try:
#     result = 10 / 0
# except ZeroDivisionError:
#     print("Cannot divide by zero!")
# except ArithmeticError:
#     print("Arithmetic error occurred!")
# except Exception as e:
#     print(f"Some other error: {e}")

# Catching Exception catches all exceptions (except system exits)
# try:
#     risky_code()
# except Exception as e:
#     print(f"An error occurred: {e}")

Key points:

  • BaseException — root of all exceptions
  • Exception — base class for most exceptions
  • More specific exceptions are subclasses
  • You can catch specific exceptions or general ones

Quick Check: What is the base class for most exceptions? (Answer: Exception)

Common Mistakes

12

Things to Watch Out For

Using a Bare Except

# WRONG — catches everything, hides errors
try:
    result = 10 / 0
except:  # Bare except
    print("Something went wrong")

# CORRECT — catch specific exceptions
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Not Reading the Error Message

# WRONG — ignoring the error message
# Traceback (most recent call last):
#   File "", line 1, in 
# TypeError: 'int' object is not iterable

# CORRECT — read and understand the error
# The error says you're trying to iterate over an integer
# Fix: Use a list or range instead

Handling the Wrong Exception Type

# WRONG — trying to catch the wrong exception
try:
    int("hello")
except TypeError:  # Wrong — ValueError is raised
    print("Type error!")

# CORRECT — catch the correct exception
try:
    int("hello")
except ValueError:
    print("Value error!")

Quick Check: What is the most common mistake with exception handling? (Answer: Using a bare except or catching the wrong exception type)

Try It Yourself

Experiment with different types of exceptions in the editor below. Modify the code and see what happens.

Loading Pyodide... 0%
Python Code Editor
========================================
TYPES OF EXCEPTION PRACTICE
========================================

1. TYPEERROR
TypeError caught: can only concatenate str (not "int") to str

2. VALUEERROR
ValueError caught: invalid literal for int() with base 10: 'hello'

3. INDEXERROR
IndexError caught: list index out of range

4. KEYERROR
KeyError caught: 'c'

5. ZERODIVISIONERROR
ZeroDivisionError caught: division by zero

6. NAMEERROR
NameError caught: name 'undefined_variable' is not defined

7. EXCEPTION HIERARCHY
ZeroDivisionError is a subclass of ArithmeticError

Types of exception practice complete!
🏆

You've Got It!

You now understand the different types of exceptions in Python — SyntaxError, TypeError, ValueError, IndexError, KeyError, ZeroDivisionError, FileNotFoundError, AttributeError, NameError, and the exception hierarchy.

Quick Quiz

Test what you've learned:

1. What exception is raised when you try to divide by zero?
2. What is the difference between TypeError and ValueError?
3. What exception is raised when accessing a non-existent dictionary key?
4. What is the base class for most exceptions in Python?
5. What is the safest way to access a dictionary key?

Frequently Asked Questions

What is the most common exception in Python? ▼

The most common exceptions are TypeError, ValueError, IndexError, KeyError, and NameError. SyntaxError is also very common for beginners.

What is the difference between IndexError and KeyError? ▼

IndexError occurs when accessing a non-existent index in a sequence (list, tuple). KeyError occurs when accessing a non-existent key in a dictionary.

Can I create my own exception types? ▼

Yes, you can create custom exceptions by inheriting from the Exception class. This is covered in the "User Defined Exception" tutorial.

What is the best practice for exception handling? ▼

Catch specific exceptions rather than using a bare except. Handle only the exceptions you expect, and let others propagate. Always log or report exceptions appropriately.

What is the exception hierarchy? ▼

All exceptions inherit from BaseException. Most exceptions inherit from Exception. Specific exceptions like TypeError, ValueError, etc. are subclasses of Exception.

What's a common interview question about exception types? ▼

Common questions include: "What is the difference between TypeError and ValueError?" and "What is the base class for all exceptions in Python?"

Where to Go From Here

Now that you understand the types of exceptions, check out these related topics:

Exception Handling

Learn how to handle exceptions with try-except.

Learn More →

User Defined Exception

Create your own custom exceptions.

Learn More →

Logging Exception

Learn how to log exceptions for debugging.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Error vs Exception Next: Exception Handling →