Python Files & Errors
Python try except
The try/except block lets your program catch an error the moment it happens and respond sensibly, instead of crashing with a traceback in front of the user.
Basic try/except
Code that might fail goes inside the try block. If an exception occurs, Python immediately jumps to the matching except block instead of stopping the whole program.
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")Catching Specific vs Broad Exceptions
Always try to catch the most specific exception type you expect, like ValueError or KeyError. A bare except: (or except Exception:) catches everything, including bugs you did not anticipate, which can hide real problems.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a valid whole number.")Avoid bare except: blocks in real projects — they silently swallow errors like typos and make bugs much harder to find.
Handling Multiple Exception Types
You can stack several except blocks to handle different error types differently, or group related types in one tuple.
try:
data = {"marks": 90}
value = int(data["name"])
except KeyError:
print("That key does not exist.")
except (ValueError, TypeError):
print("The value could not be converted.")else and finally
The else block runs only if the try block succeeds with no exception. The finally block always runs — whether an exception happened or not — making it perfect for cleanup work like closing a file or a database connection.
try:
number = int("42")
except ValueError:
print("Conversion failed")
else:
print("Conversion succeeded:", number)
finally:
print("This always runs, error or not.")- try holds risky code that might raise an exception.
- except catches and handles a specific exception type.
- else runs only when no exception occurred.
- finally always runs, useful for cleanup like closing files.
You can access the exception object itself with "except ValueError as e:" and then print(e) to see its message.
