DevNet Associate (DEVASC) v1.0Software Development and DesignMedium
A developer is writing a Python script to interact with a network device using its CLI. The script needs to send commands and parse the output. To make the script robust, the developer wants to ensure that if a command fails or the device becomes unreachable, the script logs the error and continues execution for other devices, rather than crashing. Which Python construct should be used to handle potential runtime errors gracefully?
- Atry/except blocks
- Bif/else statements
- CAssertions
- Dfor loops
Show answer & explanationAnswer & explanation
Correct answer: A. try/except blocks
A `try/except` block is Python's primary mechanism for handling exceptions (runtime errors). Code that might raise an error is placed in the `try` block, and code to handle specific errors is placed in the `except` block, allowing the program to recover gracefully and continue execution.
Why the other options are wrong
- B. `if/else` statements handle conditional logic, but they cannot catch unexpected runtime errors (exceptions) like a network timeout or a `KeyError`.
- C. Assertions are used to check if a condition is true; if not, they raise an `AssertionError`, typically used for debugging or internal consistency checks, not for handling external runtime errors gracefully.
- D. `for` loops are for iteration and do not provide a mechanism for handling exceptions that occur within the loop body.
Python Try-Except Block
A `try/except` block in Python is used for error handling. Code that might raise an exception (runtime error) is placed inside the `try` block. If an exception occurs, the `except` block catches it, allowing the program to handle the error and continue execution.
- Prevents script crashes due to unexpected errors.
- Can catch specific types of exceptions.
- Includes optional `else` (if no exception) and `finally` (always executes) blocks.
- Essential for creating robust and fault-tolerant applications.
Memory trick: Try to run, except when errors come, then handle.