Files & Error Handling

Try-Except: Handling Errors

Error Handling: Try-Except 🛡️

Handle errors gracefully instead of crashing.

Basic Try-Except

try:
    number = int(input("Enter a number: "))
    print(f"You entered: {number}")
except:
    print("That's not a valid number!")

Catching Specific Errors

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid value!")

The Finally Block

Always runs, whether there's an error or not:

try:
    file = open("data.txt")
    # Do something
except FileNotFoundError:
    print("File not found!")
finally:
    print("Cleanup complete")

Else Block

Runs if NO exception occurred:

try:
    number = int("42")
except ValueError:
    print("Error!")
else:
    print(f"Success! Number is {number}")
Visualizer
$ python divide.py
5.0 Cannot divide by zero!

Interactive Visualization

python
Loading...
Output
Run execution to see output...