Course Content
🎁 Bonus Modules (Integrated Throughout)
Data Analytics
Error Handling

When writing code, it’s common to encounter errors. Some errors stop the program from running — these are known as exceptions. Python gives us tools to manage these errors gracefully without crashing the program.


What is an Exception?

An exception is an error that occurs during the execution of a program. For example:

print(10 / 0) # This will raise a ZeroDivisionError

Common Built-in Exceptions

Here are a few common exceptions:

Exception Name Happens When…
ZeroDivisionError You divide a number by zero
ValueError A function receives an invalid value
IndexError List index is out of range
KeyError A key is not found in a dictionary
TypeError Operation is applied to wrong type

The try-except Block

 

To handle exceptions, use try-except. This allows your program to continue running even if an error occurs.

try:
number = int(input("Enter a number: "))
result = 10 / number
print(result)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter a valid number.")

Using else with try-except

You can add an else block to run code if no exception occurs.

try:
age = int(input("Enter your age: "))
except ValueError:
print("Not a valid number.")
else:
print(f"You are {age} years old.")

Using finally

The finally block always runs, whether there is an exception or not. It’s useful for cleanup.

try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Attempt to read file is complete.")

Raising Your Own Errors

Sometimes, you may want to create errors on purpose using the raise keyword.

age = -5
if age < 0:
raise ValueError("Age cannot be negative")

Why Use Error Handling?

  • Prevent program crashes
  • Display user-friendly messages
  • Handle expected or unexpected inputs safely
  • Maintain control of the program’s flow

Summary

  • Use try to test code that may cause an error.
  • Use except to handle specific errors.
  • Use else if no error occurs.
  • Use finally to execute code no matter what.
  • Use raise to throw your own exceptions if needed.
0% Complete
WhatsApp Icon

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.