Exception Handling
Errors happen – files might not exist, network requests fail, user inputs invalid data. Exception handling allows your program to gracefully respond to errors instead of crashing. Python uses `try`, `except`, `else`, and `finally` blocks.
Basic try-except
Place risky code inside `try`, and handle exceptions in `except`.
try:
num = int(input("Enter a number: "))
result = 10 / num
print(result)
except ValueError:
print("That's not a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except Exception as e:
print(f"Unexpected error: {e}")
else and finally
- `else` runs if no exception occurred.
- `finally` always runs, used for cleanup (closing files, etc.).
try:
file = open("test.txt", "r")
except FileNotFoundError:
print("File not found.")
else:
content = file.read()
print(content)
file.close()
finally:
print("Cleanup done.")
Raising Exceptions
Use `raise` to trigger an exception manually.
if age < 0:
raise ValueError("Age cannot be negative.")
Two Minute Drill
- Use `try`/`except` to handle errors gracefully.
- Catch specific exception types to handle different errors.
- `else` runs if no exception; `finally` always runs.
- `raise` can be used to trigger exceptions.
- Never catch everything with `except:`; be specific.
Need more clarification?
Drop us an email at career@quipoinfotech.com
