14/2070
Error Handling · Page 1 of 1

Try / Except / Finally

12 min Beginner

Error Handling

What is an Exception?

In programming, an exception is an event that disrupts the normal sequential flow of execution. When Python encounters an error at runtime — such as dividing by zero, reading a missing file, or applying an operation to the wrong type — it raises an exception object. This object propagates up the call stack until it reaches code that explicitly handles it. If nothing handles it, the program terminates and prints a traceback.

In Data Science, data is messy and unpredictable. A division by zero, a missing file, or wrong data types will crash your entire pipeline if you don't handle exceptions properly.

The Try/Except Block

try:
    # Risky code
    result = 10 / 0
except ZeroDivisionError:
    # What to do if it fails
    print("Cannot divide by zero!")
finally:
    # Always runs (cleanup)
    print("Execution finished.")

Common Data Science Exceptions

  • KeyError: Accessing a missing dictionary key or Pandas column.
  • TypeError: Applying math to strings.
  • IndexError: Accessing a list index that doesn't exist.
  • ValueError: Converting a non-numeric string to float.

💡 Best Practice: Never use a "bare except" (just except:). Always catch the specific error so you don't accidentally hide bugs.

main.py
Loading...
OUTPUT
Click "Run Code" to execute…