Labs ICT
๐ŸŽ“ SIWES/IT Login

Try & Except

1 min read | Python Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

Basic try-except

Use try to wrap risky code and except to handle errors gracefully. The program won't crash โ€” it runs the except block instead.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Can't divide by zero!")

Multiple Except Clauses

You can catch different exception types separately. Each except block handles a specific error, so you can respond appropriately.

try:
    value = int(input("Enter a number: "))
    result = 10 / value
except ValueError:
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("Zero is not allowed.")
except Exception as e:
    print(f"Something else: {e}")

Else and Finally

The else block runs when no exception occurs. The finally block always runs โ€” perfect for cleanup like closing files.

try:
    file = open("test.txt", "r")
except FileNotFoundError:
    print("File not found.")
else:
    print("File opened successfully.")
    file.close()
finally:
    print("This always runs.")

๐Ÿงช Quick Quiz

Which keyword catches exceptions in Python?