python try/catch exception handler
π§ Topic: Python try, except, else, finally for DevOps Engineers
π§βπ« Why It Matters for DevOps
As a DevOps engineer, you automate tasks, deal with file systems, APIs, and system commands. Things can go wrong β files might not exist, servers may be down, or a user might give bad input. Exception handling makes your automation scripts reliable.
πΉ 1. What is try and except?
As Corey Schafer says:
βTry-except allows us to anticipate and handle runtime errors so our programs don't crash unexpectedly.β
β Syntax
try:
# Code that might throw an error
except SomeError:
# Code that runs if an error occurs
π§ͺ Example 1: Divide by Zero
try:
result = 10 / 0
except ZeroDivisionError:
print("β Cannot divide by zero.")
π§ Scenario:
You are reading a configuration value from a file and converting it to an integer.
β Without try-except: Code crashes if file is missing or data is bad
# config.txt is missing OR has invalid content (e.g., "abc")
with open("config.txt") as f:
content = f.read()
value = int(content) # π₯ CRASHES if content is not an integer
print("Configuration value is:", value)
𧨠Possible Output (if file is missing or content is "abc"):
Traceback (most recent call last):
File "script.py", line 2, in <module>
with open("config.txt") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'config.txt'
Or:
ValueError: invalid literal for int() with base 10: 'abc'
β
With try-except: Gracefully handles errors
try:
with open("config.txt") as f:
content = f.read()
value = int(content)
print("β
Configuration value is:", value)
except FileNotFoundError:
print("β Error: config.txt file is missing.")
except ValueError:
print("β Error: config.txt contains invalid number.")
finally:
print("π Attempted to read configuration.")
π― Output if file is missing:
β Error: config.txt file is missing.
π Attempted to read configuration.
π― Output if file has "abc":
β Error: config.txt contains invalid number.
π Attempted to read configuration.
β Visual Comparison Summary
| Feature | Without try | With try-except |
| Missing file | Crashes | Gracefully prints error |
| Invalid content (e.g., abc) | Crashes with ValueError | User-friendly error message |
| Script continues after error? | β No | β Yes |
| Logs / final actions run? | β No | β
Yes via finally |
πΉ 2. Catching Multiple Exceptions
Inspired by Al Sweigart ("Automate the Boring Stuff with Python"):
βCatching only specific exceptions avoids hiding bugs.β
β Example 2: Catch File & Value Errors
try:
with open("config.txt") as f:
content = int(f.read())
except FileNotFoundError:
print("β File not found.")
except ValueError:
print("β Couldn't convert file content to integer.")
πΉ 3. Catch-All (Not Recommended Unless Logging)
try:
risky_task()
except Exception as e:
print(f"βCaught error: {e}")
β Mosh Hamedani warns: Only use this for logging or fallback, not to ignore errors.
πΉ 4. The else Block (Optional)
Use else to run code only if there was no error.
try:
x = 1 / 1
except ZeroDivisionError:
print("β Division error.")
else:
print("β
Success! No error.")
πΉ 5. The finally Block
Always runs, no matter what β used to clean up resources.
try:
file = open("log.txt", "w")
file.write("Logging some event.")
except Exception:
print("β Something went wrong.")
finally:
file.close()
print("π File closed.")
πΉ 6. Real DevOps Example β Check EC2 Instance Log
import subprocess
try:
result = subprocess.check_output(["aws", "ec2", "describe-instances"])
print("β
EC2 info collected.")
except subprocess.CalledProcessError as e:
print("β AWS CLI command failed:", e)
πΉ 7. Best Practices for DevOps Scripts
β
Catch specific exceptions
β
Use finally to close files/connections
β
Don't silence errors β log them
β
Use try-except for API, file, shell commands
β
Validate user input with try
π§βπ¬ Practice Tasks for Students
Read a file that doesn't exist β handle
FileNotFoundError.Get integer input from user and divide 100 by it β handle
ValueErrorandZeroDivisionError.Call an API (use
requests.get) β simulate a bad URL and handle exceptions.Use
subprocess.runto runlsordirβ handleCalledProcessError.
β¨ Wrap-Up Quote
"Errors should never pass silently. Unless explicitly silenced."
β The Zen of Python (PEP 20)
π Homework (DevOps style)
Create a Bash-to-Python wrapper:
Script runs a shell command like
df -husing PythonIf it fails, logs the error to a file
Always writes βJob completedβ to the log using
finally
