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 ZeroDivisionErrorYou 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.
Data is often messy or unpredictable. Using error handling helps you write more robust code that doesn’t break when unexpected values appear.