Exception Handling
Exception Handling lets your program respond gracefully to errors that occur while it's running, instead of crashing outright - a critical skill for writing reliable, production-ready code.
The try-except Block
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Handling Multiple Exception Types
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("That's not a valid number")
except ZeroDivisionError:
print("You can't divide by zero!")
The else and finally Clauses
The else block runs only if no exception occurred, and the finally block always runs, whether or not an exception was raised - commonly used for cleanup actions like closing a file.
try:
file = open("data.csv")
except FileNotFoundError:
print("File not found")
else:
print("File opened successfully")
file.close()
finally:
print("Done attempting to open the file")
Raising Your Own Exceptions
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
try:
set_age(-5)
except ValueError as e:
print("Error:", e)
Always catch specific exception types (like
ValueError or FileNotFoundError) rather than using a bare except:, which silently catches every possible error and can hide real bugs in your code.Coming Up Next
Next, the course moves into the basics of Data Analysis, setting the stage for hands-on work with NumPy arrays.