Skip to main content

Command Palette

Search for a command to run...

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

FeatureWithout tryWith try-except
Missing fileCrashesGracefully prints error
Invalid content (e.g., abc)Crashes with ValueErrorUser-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.")

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

  1. Read a file that doesn't exist β€” handle FileNotFoundError.

  2. Get integer input from user and divide 100 by it β€” handle ValueError and ZeroDivisionError.

  3. Call an API (use requests.get) β€” simulate a bad URL and handle exceptions.

  4. Use subprocess.run to run ls or dir β€” handle CalledProcessError.


✨ 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 -h using Python

  • If it fails, logs the error to a file

  • Always writes β€œJob completed” to the log using finally