micheledpierri.com

  • HOME
    • Python
    • Statistics
    • Data Analysis
    • Machine Learning
  • WRITINGS
  • VISIONS
  • ABOUT
Home / Python / Errors, Exceptions, and Robust Code
Children dressed in lab coats are studying a python

Errors, Exceptions, and Robust Code

Lesson Objectives

By the end of this lesson, you will be able to:

  • Understand the difference between errors and exceptions
  • Recognize the most common Python exceptions
  • Handle errors using try / except
  • Write safer and more robust analytical code

This lesson is crucial:

real-world data is messy, and code must fail gracefully.


1️⃣ Errors vs Exceptions

In Python:

  • Errors indicate problems detected before execution (syntax errors)
  • Exceptions occur during execution (runtime errors)

Example of a syntax error:

if x > 0
    print(x)

Python cannot even start executing this code.


2️⃣ Runtime Errors (Exceptions)

Runtime errors happen while the program is running.

Example:

x = int("abc")

Error raised:

ValueError

The program stops unless the exception is handled.


3️⃣ Common Python Exceptions

Some exceptions appear frequently in analytical code:

  • ValueError → wrong value type
  • TypeError → incompatible types
  • ZeroDivisionError → division by zero
  • FileNotFoundError → missing file
  • IndexError → invalid index access
  • KeyError → missing dictionary key

Recognizing them saves hours of debugging.


4️⃣ Handling Exceptions with try / except

Basic structure:

try:
    x = int("abc")
except ValueError:
    print("Conversion failed")

What happens:

  • Python tries to execute the try block
  • if the specified exception occurs, the except block runs
  • the program continues safely

5️⃣ Catching Multiple Exceptions

You can handle different exceptions separately:

try:
    x = int(input("Enter a number: "))
    y = 10 / x
except ValueError:
    print("Not a valid number")
except ZeroDivisionError:
    print("Division by zero is not allowed")

This pattern is common in data input validation.


6️⃣ The else and finally Blocks

else

Runs only if no exception occurs:

try:
    x = int("10")
except ValueError:
    print("Error")
else:
    print("Success:", x)

finally

Always runs, whether an exception occurred or not:

try:
    file = open("data.txt")
except FileNotFoundError:
    print("File missing")
finally:
    print("Operation completed")

Useful for cleanup operations.


7️⃣ When to Use Exception Handling

Use try / except when:

  • dealing with external input
  • reading files
  • parsing data
  • performing risky operations

Do not use it to hide programming errors.

Rule:

Exceptions should handle expected problems, not mask bugs.


8️⃣ Error Handling in Data Analysis

In data workflows, exceptions help you:

  • skip corrupted records
  • validate input data
  • prevent pipeline crashes
  • log problems for later inspection

Robust pipelines anticipate failure.


FAQ — Frequently Asked Questions

Q: Should I wrap all code in try/except?

A: No. Only wrap code that can reasonably fail.

Q: Is catching Exception bad practice?

A: Yes, unless you re-raise or log appropriately.

Q: Can I create my own exceptions?

A: Yes, but this is an advanced topic.

Q: Do exceptions slow down code?

A: Negligibly in normal use; clarity matters more.


Exercises

Exercise 1

Write code that raises a ZeroDivisionError.

Exercise 2

Handle the error from Exercise 1 using try / except.

Exercise 3

Convert user input to an integer safely.

Exercise 4

Handle both ValueError and ZeroDivisionError.

Exercise 5

Use else to print a success message.

Exercise 6

Use finally to print "Done".

Exercise 7

Predict the output:

try:
    x = int("5")
except ValueError:
    print("Error")
else:
    print(x)

Exercise 8

Explain why this is bad practice:

try:
    x = 1 / 0
except:
    pass

Exercise 9

Write code that safely opens a file.

Exercise 10

Explain why exception handling is critical in data analysis.


Solutions

Exercise 1

1 / 0

Exercise 2

try:
    1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Exercise 3

try:
    x = int(input("Enter a number: "))
except ValueError:
    print("Invalid input")

Exercise 4

try:
    x = int(input())
    y = 10 / x
except ValueError:
    print("Not a number")
except ZeroDivisionError:
    print("Division by zero")

Exercise 5

try:
    x = int("10")
except ValueError:
    print("Error")
else:
    print("Success")

Exercise 6

try:
    x = int("10")
finally:
    print("Done")

Exercise 7

# Output: 5

Exercise 8

# It hides errors and makes debugging impossible

Exercise 9

try:
    with open("data.txt", "r") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found")

Exercise 10

# Real data is messy; robust code prevents pipeline failures


Next Lesson Preview

In Lesson 10, we will introduce:

  • classes and objects
  • __init__ and instance attributes
  • why OOP matters even in data-centric code

This is where Python moves from scripts to structured systems.

Cite this article

Pierri, M. D. (2026). Errors, Exceptions, and Robust Code. micheledpierri.com. Permalink

Share:Email·LinkedIn
Previous← Modules, Packages, and File HandlingNextObject-Oriented Programming (OOP) in Python →
Python
  1. Why Python
  2. Python & VS Code Setup (From Zero to a Professional Environment)
  3. Variables, Naming Rules, and Basic Syntax
  4. Core Data Types in Python
  5. Control Flow: Conditions and Loops
  6. Functions and Code Reusability
  7. Collections: Lists, Tuples, Sets, and Dictionaries
  8. Modules, Packages, and File Handling
  9. Errors, Exceptions, and Robust Code
  10. Object-Oriented Programming (OOP) in Python
  11. Intermediate Python: Writing Clean, Pythonic Code
  12. Python Wrap-Up Lesson: A Mini Cardiology Risk-Factor Audit (Step-by-Step)
© 2024–2026 micheledpierri.com · Privacy Policy · Impressum