Skip to main content

Exception Handling & Data Handling

In real-world applications, systems must be robust against failures. Exception Handling allows you to gracefully recover from runtime errors. Furthermore, backend applications frequently exchange and process data stored in Text, CSV, and JSON formats.

Topics Covered

In this module, you’ll learn:
  1. Exception Handling: The try-except-else-finally block.
  2. Custom Exceptions: Inheriting from the base Exception class for domain-specific errors.
  3. Data Handling (File I/O)
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 Download
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download

1. Exception Handling

An exception is an error that occurs during the execution of a program. If not handled, the program will terminate abruptly (crash). Exception handling allows you to catch these errors and respond gracefully.

The try-except-else-finally Block

Raising Exceptions (raise)

You can trigger exceptions intentionally in your code using the raise keyword.

Exercise 1

Write a function safe_divide(a, b) that performs division. If a ZeroDivisionError or TypeError occurs, catch it and return None along with a descriptive print message.

2. Custom Exceptions

When building complex applications (like APIs), Python’s built-in exceptions (like ValueError or KeyError) might not be expressive enough. You can create your own custom exceptions by inheriting from the base Exception class.

Exercise 2

Define a custom exception InvalidAgeError. Write a function verify_age(age) that raises this exception with the message "Age must be between 0 and 120" if the age is outside this range.

3. Data Handling (File I/O)

Backend services constantly read configurations, import CSV logs, or exchange JSON payloads.

Text Files

Always use the context manager (with statement) when working with files. It ensures that the file is closed automatically after execution, preventing memory leaks.

CSV Data (Comma Separated Values)

Python’s built-in csv module provides simple utilities to read and write rows of tabular data.

Writing CSV

Reading CSV

Reading CSV as Dictionaries (DictReader)

DictReader maps the header row to keys, turning each row into a dictionary.

JSON Data (JavaScript Object Notation)

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It is the standard format for exchanging data in modern web APIs because it is easy for both humans to read and machines to parse.

JSON Data Types & Type Mapping

JSON supports a limited set of data types. When you load a JSON payload into Python or convert Python objects to JSON, Python handles the conversions automatically based on the following type mapping: Python’s built-in json module provides four primary functions to translate between these types:
  • json.dumps() / json.loads(): Convert between Python objects and JSON strings.
  • json.dump() / json.load(): Read and write JSON files.

Exercise 3

Create a JSON file named config.json containing {"debug": true, "version": "1.0"}. Write a Python script to read this file, set "debug" to false, add a new key "updated": true, and save it back to the file.

Practice

To reinforce what you’ve learned in this section, practice with the interactive follow-along notebook:

Follow-Along Practice

Practice exception handling (try-except-else-finally), raising custom exceptions, and reading/writing text, CSV, and JSON files.💻 VS Code | 🚀 Colab | 📥 Download

Summary

In this module, you learned how to handle runtime errors using try-except blocks, build custom exceptions to represent business logic failures, and parse/generate files in Text, CSV, and JSON formats.