Error handling with try and except
What is it?
In Python, the try and except blocks are used to handle exceptions (errors) gracefully, preventing your program from crashing unexpectedly.
Keywords
try: The block of code you want to test for errors.except: The block of code that runs if an error occurs in thetryblock.else: (Optional) Runs only if no error occurs in thetryblock.finally: (Optional) Runs no matter what — useful for cleanup actions.
Basic Syntax
try:
# risky code
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")Full Example with All Keywords
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Division by zero error")
else:
print("Result is", result)
finally:
print("Execution complete")
divide(10, 0)
divide(10, 2)Output:
Division by zero error
Execution complete
Result is 5.0
Execution completeUse Cases
-
Handling file operations:
try: with open("file.txt") as f: content = f.read() except FileNotFoundError: print("File not found") -
Validating user input:
try: age = int(input("Enter your age: ")) except ValueError: print("That's not a valid number!")
Why Use try/except?
- Keeps your program from crashing.
- Provides user-friendly error messages.
- Lets you handle specific errors in different ways.
Summary:
- Use
try/exceptto manage errors. elseruns when no error occurs.finallyruns no matter what.
Let me know if you want examples for specific exceptions or advanced error handling!
Interview angle 4
- “How specific should an except clause be?” - as specific as you can act on. Bare
except:catchesKeyboardInterruptandSystemExittoo;except Exceptionis the broad-but-acceptable form, and even then only at a boundary where you log and re-raise or convert. - “What does
elsedo on a try block?” - runs when no exception occurred, keeping the protected block down to the statement that can actually fail. That precision stops you accidentally catching an error from unrelated code. - “
raiseorraise from?” -raise NewError(...) from originalpreserves the cause chain, so the traceback shows both. Losing the original exception makes production debugging much harder. - “EAFP or LBYL?” - Python prefers EAFP: try it and handle the failure. It avoids a check-then-use race and is faster when the happy path dominates.