Chapter 12: Exception Handling in Python – Master Errors, Exceptions, and Robust Programming

V

Vishal Yadav | Course Instructor

Published: Jun 09, 2026 Estimated time: 10 Mins
Module Summary Learn how to handle errors gracefully in Python using try-except, finally blocks, raise statements, and custom exceptions to build reliable applications.

Introduction

Have you ever run a program that suddenly crashed because of an unexpected input, missing file, or mathematical mistake? These situations are common in software development, and without proper handling, they can cause applications to fail unexpectedly. This is where exception handling becomes an essential skill.

Exception handling allows developers to detect errors, respond appropriately, and keep applications running smoothly even when problems occur. Instead of allowing a program to terminate abruptly, Python provides mechanisms to catch and manage exceptions in a controlled manner.

In this chapter, you will learn about the different types of errors, how to use try-except blocks, the purpose of the finally block, how to generate exceptions using the raise statement, and how to create your own custom exceptions.



Understanding Errors and Exceptions

Errors occur when a program encounters a problem that prevents normal execution. Some errors can be fixed by the programmer, while others can be handled dynamically during runtime.

Python categorizes most runtime issues as exceptions, which can be detected and managed using exception handling techniques.

Types of Errors

Understanding different types of errors is the first step toward effective exception handling.

1. Syntax Errors

Syntax errors occur when Python code violates language rules.

print("Hello World"

The missing closing parenthesis causes a syntax error before the program even starts running.

2. Runtime Errors (Exceptions)

Runtime errors occur while the program is executing.

number = 10
result = number / 0

This code raises a ZeroDivisionError because division by zero is not allowed.

3. Logical Errors

Logical errors occur when a program runs successfully but produces incorrect results.

length = 10
width = 5
area = length + width
print(area)

The code executes without errors, but the area calculation is incorrect because multiplication should have been used.

Common Built-in Exceptions

  • ZeroDivisionError – Division by zero.
  • ValueError – Invalid value provided.
  • TypeError – Unsupported operation between incompatible types.
  • IndexError – Accessing an invalid list index.
  • KeyError – Accessing a non-existent dictionary key.
  • FileNotFoundError – File does not exist.
  • NameError – Using an undefined variable.


The try-except Block

The most common way to handle exceptions in Python is by using the try-except block.

Basic Syntax

try:
    # Code that may cause an exception
except:
    # Code that handles the exception

If an exception occurs inside the try block, Python immediately transfers control to the corresponding except block.

Example: Handling Division by Zero

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

Instead of crashing, the program displays a meaningful message.

Handling Multiple Exceptions

try:
    number = int(input("Enter a number: "))
    result = 100 / number
except ValueError:
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("Division by zero is not allowed.")

Different exceptions can be handled separately, making error messages more specific and useful.

Using a Generic Exception Handler

try:
    # Some operation
except Exception as error:
    print("An error occurred:", error)

This catches almost all exceptions and stores the exception object in the variable error.


The else Clause

An optional else block executes only if no exception occurs.

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("Invalid input")
else:
    print("You entered:", number)

This helps separate successful execution logic from exception handling logic.

The finally Block

The finally block contains code that executes regardless of whether an exception occurs.

Why Use finally?

It is commonly used for cleanup operations such as closing files, releasing resources, or terminating connections.

Syntax

try:
    # Risky code
except:
    # Handle exception
finally:
    # Always executes

Example

try:
    file = open("data.txt
V
COURSE INSTRUCTOR

Vishal Yadav

A specialist dedicated to publishing high-quality, readable insights on technology, leadership, and digital growth.