Next →

What is an Exception?

An exception is an error that occurs during code execution. For example, dividing by zero or trying to access an index that doesn’t exist.

Example:

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

Try and Except

You can handle errors using a try and except block. This prevents your program from crashing.

Example:

try:    
print(10 / 0)
except ZeroDivisionError:    
print("You can't divide by zero!")

The code inside try runs first. If it causes an error, Python runs the code in except.

Why This Matters in Analytics

Data is often messy or unpredictable. Using error handling helps you write more robust code that doesn’t break when unexpected values appear.