Exception handling & Types of Errors in Python Programming

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

  • Create lists

    In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods: 1. Direct Initialization (Using Square Brackets []) The simplest way to create a list is by enclosing elements in square brackets []. Example: python empty_list = [] numbers = [1, 2, 3, 4] mixed_list = [1, “hello”, 3.14,…

  • AttributeError: ‘NoneType’ Error in Python re

    AttributeError: ‘NoneType’ Error in Python re This error occurs when you try to call match object methods on None instead of an actual match object. It’s one of the most common errors when working with Python’s regex module. Why This Happens: The re.search(), re.match(), and re.fullmatch() functions return: When you try to call methods like .group(), .start(), or .span() on None, you get this error. Example That Causes…

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • Generalization vs. Specialization

    Object-Oriented Programming: Generalization vs. Specialization Introduction Inheritance in OOP serves two primary purposes: Let’s explore these concepts with clear examples. 1. Specialization (Extending Functionality) Specialization involves creating a new class that inherits all features from a parent class and then adds new, specific features. The core idea is reusability—you build upon what already exists. Key Principle: Child Class =…

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

Leave a Reply

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