Python for Network Engineers
Exceptions & Safe Automation
What you'll learn
- What an exception is, and why network scripts hit them constantly
- How try / except catches an error instead of letting it stop the script
- The common causes of failure in network automation: unreachable, timeout, bad auth, invalid data, command failure
- Why one failing device shouldn't be allowed to stop an entire automation run
- Why broad exception handling is a beginner starting point, not a production best practice
Listen to a guided explanation of this lesson.
Spoken narration isn't supported in this browser.
What an exception actually is
An exception is what Python raises when something goes wrong while a script is running — not a syntax mistake caught before it even starts, but a real-world problem that only shows up once the code actually executes: a device that doesn't respond, a file that doesn't exist, a value that isn't the type you expected.
Network automation runs into exceptions constantly, for reasons that should sound familiar from "Validation, Safety & Failure Handling": a switch can be unreachable, slow to respond, reject your credentials, or reject a specific command — every one of those, in real Netmiko-based code, shows up as an exception.
Without handling it
Left alone, an exception stops the script immediately at the line where it happened — everything after that line, including every device further down a device list, never runs. That's the exact problem this lesson solves.
try / except
try:
result = 10 / 0
except:
print("Something went wrong")Python attempts everything inside the try block. Dividing by zero raises an exception on that line — instead of crashing the whole script, Python jumps straight to the except block and runs that instead. Output: "Something went wrong", and the script keeps running afterward.
The pattern in a loop, connecting this directly back to device inventory:
devices = [
{"hostname": "SW1", "reachable": True},
{"hostname": "SW2", "reachable": False},
{"hostname": "SW3", "reachable": True},
]
for device in devices:
try:
if not device["reachable"]:
raise ConnectionError(f"{device['hostname']} did not respond")
print(f"{device['hostname']}: check complete")
except ConnectionError as e:
print(f"{device['hostname']}: skipped — {e}")raise deliberately triggers an exception here, standing in for what a real connection attempt would do on its own if a switch didn't respond. The except block catches it, prints a clear message, and — critically — the loop moves on to SW3 instead of stopping.
The common ways a network script fails
- Unreachable device — no path to the device at all (down, wrong IP, blocked by an ACL).
- Timeout — a connection was attempted but the device didn't respond in time.
- Authentication failure — the device rejected the credentials.
- Invalid data — something in the inventory or input file isn't what the script expected (a missing key, a value of the wrong type).
- Command failure — the connection worked, but a specific command was rejected by the device.
Every one of these is a category from "Validation, Safety & Failure Handling," two lessons of theory made concrete here as things a try/except around a device operation is specifically there to catch.
Broad except: fine for now, not the finish line
Every example in this lesson uses a bare except: or catches one specific exception — that's the right level for learning the concept. It's worth being honest, though: production automation code usually catches specific exception types (a real Netmiko-based script distinguishes a timeout from an authentication failure, because they need different responses), rather than one broad except: that treats every possible problem identically.
Why not just catch everything, always?
A bare except: also catches mistakes in your own code — a typo, a bug — and silently treats them the same as "the device was unreachable." That can hide real problems instead of surfacing them. For this module, focus on the concept: catching an error keeps a script running past one failed device. Narrowing exactly what you catch, and how you respond to each kind, is a skill that develops with practice — including in the Netmiko module later in this curriculum, once real connection exceptions are involved.
Why one failure shouldn't stop the run
- Device 1success
- Device 2timeout → handled → continue
- Device 3success
This is the payoff of putting try/except inside the loop rather than around the whole script: device 2 failing doesn't take device 1's or device 3's results down with it. A script checking 50 switches that stops entirely because switch 2 timed out has thrown away 48 perfectly good results over one bad connection — exactly the mistake "Network Automation Fundamentals" warned against, now avoidable with three lines of Python.
Key takeaways
- An exception is what Python raises when something goes wrong during execution — a device that doesn't respond, a missing value, a rejected command.
- try/except catches an exception where it happens and runs alternative code instead of letting the script crash.
- The common failure categories — unreachable, timeout, authentication failure, invalid data, command failure — are exactly what real try/except blocks in network automation are written to catch.
- Broad except: is a fine starting point for learning; production code narrows down to specific exception types so different failures get different responses.
- Putting try/except inside a loop means one device's failure doesn't cost you every other device's results — the loop keeps going.