Exception handling & Types of Errors in Python Programming

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

Exception handling in Python is a process of responding to and managing errors that occur during a program’s execution, allowing the program to continue running without crashing. These errors, known as exceptions, disrupt the normal flow of the program and can be caught and dealt with using a try...except block.


How It Works

The core of exception handling involves a try block and one or more except blocks.

  • try block: You place the code that might cause an error inside this block. If an exception occurs, Python immediately stops executing the code in the try block and looks for a matching except block.
  • except block: This block contains the code that runs when a specific type of exception is caught. You can specify which exception you’re handling (e.g., ZeroDivisionError, ValueError).

Types of Errors in Python Programming

Python errors can be broadly categorized into three main types:

1. Syntax Errors

Occur when the Python parser encounters incorrect syntax.

python

# Examples of syntax errors
print("Hello world"  # Missing closing parenthesis
if x = 5:            # Using = instead of ==
def function:        # Missing parentheses for parameters

Characteristics:

  • Detected during parsing/compilation
  • Prevent the program from running
  • Easy to spot with proper code editors

2. Runtime Errors (Exceptions)

Occur during program execution when an operation is attempted that is impossible to execute.

Common Runtime Errors:

ZeroDivisionError

python

result = 10 / 0  # Division by zero

TypeError

python

"5" + 3           # Adding string and integer
len(5)            # len() on integer

ValueError

python

int("abc")        # Invalid conversion
float("12.34.56") # Invalid float format

IndexError

python

my_list = [1, 2, 3]
print(my_list[5]) # Index out of range

KeyError

python

my_dict = {"a": 1, "b": 2}
print(my_dict["c"]) # Key doesn't exist

FileNotFoundError

python

with open("nonexistent.txt", "r") as file:
    content = file.read()

AttributeError

python

x = 5
x.append(10)      # Integer has no append method

ImportError

python

import non_existent_module  # Module doesn't exist

NameError

python

print(undefined_variable)  # Variable not defined

KeyboardInterrupt

python

# Occurs when user presses Ctrl+C

3. Logical Errors

The program runs without crashing but produces incorrect results.

python

# Logical error example
def calculate_average(numbers):
    # Forgot to divide by length - logical error
    return sum(numbers)  # Should be: return sum(numbers) / len(numbers)

result = calculate_average([1, 2, 3, 4, 5])
print(result)  # Output: 15 (should be 3.0)

Characteristics:

  • Hardest to detect and debug
  • Program runs but gives wrong output
  • Requires careful testing and debugging

Less Common but Important Errors

MemoryError

python

# When program runs out of memory
huge_list = [0] * (10**10)  # May cause MemoryError

RecursionError

python

def infinite_recursion():
    return infinite_recursion()  # Maximum recursion depth exceeded

infinite_recursion()

OverflowError

python

import math
math.exp(1000)  # Result too large to represent

StopIteration

python

# Raised by next() when iterator has no more items
iterator = iter([1, 2])
next(iterator)  # 1
next(iterator)  # 2
next(iterator)  # StopIteration

Error Hierarchy

Python exceptions follow an inheritance hierarchy:

text

BaseException
 β”œβ”€β”€ SystemExit
 β”œβ”€β”€ KeyboardInterrupt
 β”œβ”€β”€ GeneratorExit
 └── Exception
      β”œβ”€β”€ StopIteration
      β”œβ”€β”€ ArithmeticError
      β”‚    β”œβ”€β”€ FloatingPointError
      β”‚    β”œβ”€β”€ OverflowError
      β”‚    └── ZeroDivisionError
      β”œβ”€β”€ AssertionError
      β”œβ”€β”€ AttributeError
      β”œβ”€β”€ BufferError
      β”œβ”€β”€ EOFError
      β”œβ”€β”€ ImportError
      β”œβ”€β”€ LookupError
      β”‚    β”œβ”€β”€ IndexError
      β”‚    └── KeyError
      β”œβ”€β”€ MemoryError
      β”œβ”€β”€ NameError
      β”‚    └── UnboundLocalError
      β”œβ”€β”€ OSError
      β”‚    β”œβ”€β”€ FileNotFoundError
      β”‚    β”œβ”€β”€ PermissionError
      β”‚    └── ...
      β”œβ”€β”€ RuntimeError
      β”‚    └── RecursionError
      β”œβ”€β”€ SyntaxError
      β”‚    └── IndentationError
      β”œβ”€β”€ TypeError
      β”œβ”€β”€ ValueError
      └── Warning

Practical Error Handling Tips

python

try:
    # Potentially problematic code
    age = int(input("Enter your age: "))
    result = 100 / age
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Age cannot be zero!")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
else:
    print(f"Result: {result}")
finally:
    print("Execution completed.")

Understanding these error types helps in writing more robust and maintainable Python code.

Similar Posts

  • start(), end(), and span()

    Python re start(), end(), and span() Methods Explained These methods are used with match objects to get the positional information of where a pattern was found in the original string. They work on the result of re.search(), re.match(), or re.finditer(). Methods Overview: Example 1: Basic Position Tracking python import re text = “The quick brown fox jumps over the lazy…

  • sqlite3 create table

    The sqlite3 module is the standard library for working with the SQLite database in Python. It provides an interface compliant with the DB-API 2.0 specification, allowing you to easily connect to, create, and interact with SQLite databases using SQL commands directly from your Python code. It is particularly popular because SQLite is a serverless database…

  • re Programs

    The regular expression r’;\s*(.*?);’ is used to find and extract text that is located between two semicolons. In summary, this expression finds a semicolon, then non-greedily captures all characters up to the next semicolon. This is an effective way to extract the middle value from a semicolon-separated string. Title 1 to 25 chars The regular…

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

  • Nested for loops, break, continue, and pass in for loops

    break, continue, and pass in for loops with simple examples. These statements allow you to control the flow of execution within a loop. 1. break Statement The break statement is used to terminate the loop entirely. When break is encountered, the loop immediately stops, and execution continues with the statement immediately following the loop. Example:…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

Leave a Reply

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