Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Errors and exceptions

Mistakes are inevitable in data work. Exception handling allows you to catch them.

Errors

  • issues/mistakes in a program that prevent it from executing successfully

  • common types include syntax errors, runtime errors, and logical errors

Exceptions

  • events that occur during the execution of a program that disrupts the normal flow of instructions

  • common examples include division by zero, accessing an index that does not exist, or trying to open a file that doesn’t exist

Common Exceptions Types:

  • ZeroDivisionError: Dividing by zero.

  • ValueError: Trying to convert text (“Five”) to a number.

  • IndexError: Trying to access item #5 in a list of only 3 items.

Handling exceptions

  • try, except, finally

    • try: Contains the block of code where an exception might occur.

    • except: Specifies the block of code to execute if an exception occurs in the try block.

    • finally: Contains code that will be executed no matter what, whether an exception occurred or not.

Output
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
Cell In[1], line 3
      1 x, y = 1, 0
----> 3 print(x/y)

ZeroDivisionError: division by zero
Output
We couldn't do the division
Output
We couldn't do the division. ERROR: division by zero
Output
We couldn't do the division. Reason: division by zero
Maybe try again next time?
Output
10.00 tons/ha
Error: Cannot divide by zero (Hectares is 0)
Error: Inputs must be numbers

File and Exception Handling Combined

Real-world data is messy. A file might be missing, or a user might enter “N/A” in a numeric column. We combine with open and try-except to build robust pipelines.

Output
Farm 001 (Palay): 2.5 ha
Farm 002 (Corn): 1.0 ha
Farm 003 (Coconut): 5.0 ha
Farm 004 (Mango): 3.2 ha
Output
Critical Error: The file 'missing_file.txt' was not found.