Skip to main content

Exception Handling

In programming, errors are inevitable. A user might enter text where a number is expected, a file might not exist, or the internet connection might fail. If we do not "handle" these errors, our program will "crash" and stop abruptly.

In Python, error handling is done using try, except, else, and finally blocks.

The try...except Block

How does it work?

  1. The code inside try runs first.
  2. If there is no exception (error), the except block is ignored and the program continues.
  3. If an exception occurs in the try, the rest of the try block is skipped, and if the type of error matches the one indicated after except, the code in the except block is executed.

Practical Example: Division by Zero

try:
print("Starting calculation...")
result = 10 / 0 # This causes a ZeroDivisionError
print("The result is:", result)
except ZeroDivisionError:
print("Error! You cannot divide by zero.")

print("The program continues to run normally.")

Handling Multiple Exceptions

You can have multiple except blocks to prepare different responses depending on the error that occurs, or even a generic block that catches everything.

try:
number = int(input("Enter a whole number: "))
# If the user enters letters, it causes a ValueError
# If they enter a number, we try to divide
result = 100 / number
except ValueError:
print("That is not a valid whole number.")
except ZeroDivisionError:
print("You entered a zero, and division by zero is not possible.")
except Exception as e:
# Catches ANY other type of error not specified above
print(f"An unexpected error has occurred: {e}")

Adding else and finally

  • else: Runs only if the try block was successful and did NOT raise any exceptions. It is useful for code that should only run if everything went well.
  • finally: Runs always, regardless of whether there was an error or not. The typical use case is for "cleaning up" resources, like closing open tools or files.
try:
file = open("data.txt", "r")
# Try to read data
except FileNotFoundError:
print("The file was not found.")
else:
print("File read successfully.")
finally:
# Ensure the file is not left open in memory, no matter what happens
print("Closing resources...")