Docsity

WGU D522 Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1, Exams of Information Technology

Toggle sidebar
bg1
Page 1
WGU D522 PYTHON FOR IT AUTOMATION API,
MAILHOG, LOGGING & EXCEPTION HANDLING
GUIDE TASK 1 & TASK 2 SUPPORT
100 QUESTIONS
TABLE OF CONTENTS
# TOPIC
1 Implement resilient Python scripts that consume REST APIs, handle HTTP status codes, and apply
retry/backoff strategies
2 Configure and validate MailHog as a local SMTP testing sink within automated workflows
3 Design structured, level-appropriate logging that supports debugging and auditability in automation
pipelines
4 Apply precise exception-handling constructs (custom exceptions, context managers, chained exceptions)
to prevent silent failures
5 Integrate API, email, logging, and exception components into a cohesive, testable automation solution
6 WGU D522 Python for IT Automation API
7 MailHog
8 Logging & Exception Handling Guide Task 1 & Task 2 Support
9 Foundations of Python for IT Automation - API Integration, MailHog Testing, Logging & Exception
Handling
10 Applied Python for IT Automation - API Integration, MailHog Testing, Logging & Exception Handling
11 Advanced Python for IT Automation - API Integration, MailHog Testing, Logging & Exception Handling
12 Python for IT Automation - API Integration, MailHog Testing, Logging & Exception Handling Review
ABSTRACT
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37

Partial preview of the text

Download WGU D522 Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1 and more Exams Information Technology in PDF only on Docsity!

WGU D522 PYTHON FOR IT AUTOMATION API,

MAILHOG, LOGGING & EXCEPTION HANDLING

GUIDE TASK 1 & TASK 2 SUPPORT

100 QUESTIONS

TABLE OF CONTENTS

TOPIC

1 Implement resilient Python scripts that consume REST APIs, handle HTTP status codes, and apply retry/backoff strategies 2 Configure and validate MailHog as a local SMTP testing sink within automated workflows 3 Design structured, level-appropriate logging that supports debugging and auditability in automation pipelines 4 Apply precise exception-handling constructs (custom exceptions, context managers, chained exceptions) to prevent silent failures 5 Integrate API, email, logging, and exception components into a cohesive, testable automation solution 6 WGU D522 Python for IT Automation API 7 MailHog 8 Logging & Exception Handling Guide Task 1 & Task 2 Support 9 Foundations of Python for IT Automation - API Integration, MailHog Testing, Logging & Exception Handling 10 Applied Python for IT Automation - API Integration, MailHog Testing, Logging & Exception Handling 11 Advanced Python for IT Automation - API Integration, MailHog Testing, Logging & Exception Handling 12 Python for IT Automation - API Integration, MailHog Testing, Logging & Exception Handling Review

ABSTRACT

This study document brings together 100 carefully worded exam questions drawn from WGU D Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1 & Task 2 Support, with the strongest emphasis placed on Implement resilient Python scripts that consume REST APIs, handle HTTP status codes, and apply retry/backoff strategies, Configure and validate MailHog as a local SMTP testing sink within automated workflows, Design structured and level-appropriate logging that supports debugging and auditability in automation pipelines. Every item follows the wording style and level of reasoning you meet in the real paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work through the set at your own pace, mark the questions that slow you down, then come back to them until the reasoning feels automatic. Learners who revise this way walk into the exam room recognising the pattern behind the questions instead of meeting them for the first time. Keep going - steady, honest practice is what turns a difficult paper into a comfortable pass.

Q1 IMPLEMENT RESILIENT PYTHON SCRIPTS THAT CONSUME REST APIS, HANDLE HTTP

STATUS CODES, AND APPLY RETRY/BACKOFF STRATEGIES

A script uses requests.get(url, timeout=5) inside a loop that runs every 60

seconds. Under sustained network degradation, the script begins raising

requests.exceptions.ReadTimeout. Which modification best preserves long-term

automation reliability while avoiding busy-waiting?

A. Wrap the call in a bare try/except and continue immediately, relying on the next loop iteration. B. Increase the timeout to 300 seconds and remove the loop delay. C. Catch ReadTimeout, apply exponential backoff with jitter, and cap retries before raising a custom exception. CORRECT D. Replace requests with urllib.request.urlopen and set a socket default timeout. RATIONALE: Exponential backoff with jitter prevents synchronized retry storms and caps resource waste, while a custom exception surfaces persistent failure. A bare except hides faults; a 300s timeout stalls the loop; swapping libraries does not address retry semantics.

Q4 IMPLEMENT RESILIENT PYTHON SCRIPTS THAT CONSUME REST APIS, HANDLE HTTP

STATUS CODES, AND APPLY RETRY/BACKOFF STRATEGIES

A function opens a file, performs an API call, then writes results. If the API call

raises, the file handle must still be released and the original exception preserved

for the caller. Which construct best satisfies both requirements?

A. try/finally with the API call in try and file.close() in finally. B. A with statement for the file and a try/except that re-raises using bare raise. CORRECT C. try/except/finally where except swallows the exception and finally closes the file. D. Nested try blocks with os._exit(1) in the inner except. RATIONALE: A context manager guarantees file closure, and a bare raise preserves the original traceback while allowing the caller to handle the error. Option A leaks on non-file exceptions if close is missed; C swallows the exception; D terminates the process abruptly.

Q5 IMPLEMENT RESILIENT PYTHON SCRIPTS THAT CONSUME REST APIS, HANDLE HTTP

STATUS CODES, AND APPLY RETRY/BACKOFF STRATEGIES

An automation script must POST JSON to an API that returns 429 with a

Retry-After header. Which implementation most correctly honors the server's

guidance while remaining resilient to a missing header?

A. Immediately retry in a tight loop until status is 200. B. Sleep for a fixed 60 seconds regardless of the header value. C. Read Retry-After, sleep that many seconds (defaulting to exponential backoff if absent), then retry up to a cap. CORRECT D. Raise a custom exception and abort the run on the first 429. RATIONALE: Honoring Retry-After respects server load directives, and a backoff default handles the missing-header case. Tight loops exacerbate throttling, fixed sleeps ignore server guidance, and aborting on first 429 defeats resilience.

Q6 IMPLEMENT RESILIENT PYTHON SCRIPTS THAT CONSUME REST APIS, HANDLE HTTP

STATUS CODES, AND APPLY RETRY/BACKOFF STRATEGIES

A developer wants a custom exception that carries an HTTP status code and the

response body while remaining catchable as a generic Exception. Which definition

achieves this most idiomatically?

A. class APIError(Exception): pass B. class APIError(Exception):\n def init(self, status, body):\n super().init(f'{status}: {body}')\n self.status = status\n self.body = body CORRECT C. APIError = Exception D. class APIError(BaseException):\n def init(self, status): self.status = status RATIONALE: Subclassing Exception with a super().init call and attached attributes preserves catchability and diagnostic context. A stores no context, C aliases rather than defines, and D subclasses BaseException, which bypasses normal except Exception handlers.

Q7 IMPLEMENT RESILIENT PYTHON SCRIPTS THAT CONSUME REST APIS, HANDLE HTTP

STATUS CODES, AND APPLY RETRY/BACKOFF STRATEGIES

An automation pipeline logs with logging.getLogger(name) but messages

from third-party libraries flood the output. Which approach best isolates

application logs while preserving library diagnostics at WARNING and above?

A. Set the root logger level to ERROR. B. Set the application logger to DEBUG and call logging.getLogger('thirdparty').setLevel(logging.WARNING). CORRECT C. Remove all handlers from the root logger. D. Disable propagation on the root logger. RATIONALE: Per-logger level control isolates verbosity: the app logger stays detailed while noisy libraries are throttled to WARNING. Raising the root to ERROR suppresses app DEBUG, removing handlers breaks output, and disabling root propagation can silence child loggers unexpectedly.

Q10 CONFIGURE AND VALIDATE MAILHOG AS A LOCAL SMTP TESTING SINK WITHIN

AUTOMATED WORKFLOWS

An automation script must call three APIs sequentially, log each attempt with

correlation IDs, and continue processing remaining APIs if one fails, while

reporting a non-zero exit code at the end. Which design best satisfies these

requirements?

A. Single try/except around all three calls that exits on first failure. B. Per-call try/except that logs with a correlation ID, records failures in a list, and sys.exit(1) if any failed. CORRECT C. Nested try/finally that re-raises the first exception and skips logging. D. Use asyncio.gather without return_exceptions and let the event loop handle errors. RATIONALE: Per-call handling with correlation IDs enables granular diagnostics and continued processing, while aggregating failures into a non-zero exit code communicates overall status. A aborts early, C skips logging and re-raises prematurely, and D without return_exceptions cancels sibling tasks.

Q11 CONFIGURE AND VALIDATE MAILHOG AS A LOCAL SMTP TESTING SINK WITHIN

AUTOMATED WORKFLOWS

A Python automation script calls an internal REST API using requests and

receives HTTP 429 with a Retry-After: 30 header. Which implementation most

correctly honors the server's rate-limiting contract while remaining resilient to

transient failures?

A. Immediately retry in a tight loop until a 200 is returned, since 429 indicates a temporary condition. B. Sleep for a fixed 1-second interval and retry up to 5 times regardless of the header value. C. Read the Retry-After value, sleep that duration (or until the reset time), then retry with exponential backoff and a capped retry count. CORRECT D. Raise an exception and terminate, because 429 responses are non-retryable client errors. RATIONALE: Retry-After explicitly tells the client how long to wait; honoring it prevents hammering the server. Combining that with exponential backoff and a retry cap balances resilience with avoiding infinite loops. Fixed short sleeps or tight loops ignore the contract, and treating 429 as fatal discards a recoverable state.

Q12 CONFIGURE AND VALIDATE MAILHOG AS A LOCAL SMTP TESTING SINK WITHIN

AUTOMATED WORKFLOWS

When configuring MailHog for an automated test suite, which SMTP setting

ensures messages sent by the application under test are captured rather than

delivered externally?

A. Point the app's SMTP host to MailHog's listener (default port 1025) and disable TLS/authentication unless MailHog is configured for it. CORRECT B. Set the app's SMTP host to the production relay and add a BCC to the MailHog address. C. Configure the app to use IMAP on port 993 so MailHog can intercept outbound mail. D. Enable STARTTLS on port 587 and set the MailHog host as the relay host. RATIONALE: MailHog acts as a fake SMTP server; the app must connect to its SMTP listener (commonly 1025) so messages are captured in its UI/API. Routing through a production relay or using IMAP does not capture outbound SMTP traffic. STARTTLS on 587 is a real-world relay pattern, not MailHog's default capture mode.

Q13 CONFIGURE AND VALIDATE MAILHOG AS A LOCAL SMTP TESTING SINK WITHIN

AUTOMATED WORKFLOWS

A module configures logging.basicConfig(level=logging.INFO) at import time. A

test later calls logging.getLogger('app').setLevel(logging.DEBUG) but sees no

DEBUG output. What is the most likely cause?

A. The logger's effective level is overridden by the root handler's level, and basicConfig only configures the root logger. B. setLevel on a named logger has no effect once basicConfig has run. C. DEBUG messages are filtered by the root logger's handler level, which remains at INFO. D. The named logger propagates to root, where the handler level (INFO) discards DEBUG records. CORRECT RATIONALE: A record must pass both the logger's level and the handler's level. Setting the named logger to DEBUG lets the record through the logger, but it propagates to the root handler configured at INFO, which drops it. The fix is to set the handler level or attach a DEBUG-level handler to the named logger.

Q16 CONFIGURE AND VALIDATE MAILHOG AS A LOCAL SMTP TESTING SINK WITHIN

AUTOMATED WORKFLOWS

In a CI pipeline, MailHog is started as a sidecar and tests query its HTTP API at

http://mailhog:8025/api/v2/messages. A test intermittently fails because the

message has not yet arrived. Which change most directly addresses the race

condition?

A. Increase the SMTP client's timeout value and resend the message. B. Add a fixed time.sleep(5) before querying the API. C. Poll the MailHog API with a bounded retry/backoff until the expected message appears or a deadline is exceeded. CORRECT D. Switch from SMTP to the MailHog HTTP send endpoint to avoid asynchronous delivery. RATIONALE: Asynchronous delivery means the message may not be indexed immediately; bounded polling with backoff handles the race deterministically. Fixed sleeps are flaky and slow, and increasing timeouts does not guarantee indexing. The HTTP send endpoint still involves asynchronous processing.

Q17 CONFIGURE AND VALIDATE MAILHOG AS A LOCAL SMTP TESTING SINK WITHIN

AUTOMATED WORKFLOWS

Which logging configuration correctly prevents duplicate log lines when a library

and the application both call logging.basicConfig?

A. Call basicConfig only in the application entry point and configure handlers explicitly; libraries should use getLogger(__name__) without adding handlers. CORRECT B. Have each module call basicConfig(force=True) to reset handlers on import. C. Set logger.propagate = False on every logger to stop duplication. D. Use logging.getLogger().addHandler in every module to ensure handlers are present. RATIONALE: Duplicate lines arise when multiple handlers are attached to the same logger chain. The convention is for libraries to only obtain loggers and for the application to configure handlers once. force=True in every module resets global state unpredictably, and blanket propagate=False can silence intended output.

Q18 CONFIGURE AND VALIDATE MAILHOG AS A LOCAL SMTP TESTING SINK WITHIN

AUTOMATED WORKFLOWS

A retry wrapper uses except Exception as e: and then raise e. Compared to a

bare raise, what is the practical consequence?

A. No difference; both preserve the original traceback identically. B. raise e resets the traceback to the current frame, obscuring the original failure site. CORRECT C. raise e suppresses the exception's message. D. A bare raise is invalid outside an except block, so raise e is required. RATIONALE: raise e re-raises the same exception object but resets its __traceback__ to the current frame, hiding where it originated. A bare raise preserves the original traceback. Both are valid inside an except block, and neither suppresses the message.

Q19 DESIGN STRUCTURED, LEVEL-APPROPRIATE LOGGING THAT SUPPORTS DEBUGGING

AND AUDITABILITY IN AUTOMATION PIPELINES

Which statement best describes the relationship between try/except/else/finally

when an exception occurs in the else block?

A. The else block runs only if no exception occurred in try; an exception in else is not caught by the associated except. CORRECT B. An exception in else is caught by the except clause of the same try. C. The finally block is skipped if else raises. D. else executes after finally and its exceptions are ignored. RATIONALE: The else clause runs only when try completes without exception, and exceptions raised there propagate outward without being handled by the same except. finally still executes regardless. Understanding this ordering is essential for correct cleanup and error propagation.

Q22 DESIGN STRUCTURED, LEVEL-APPROPRIATE LOGGING THAT SUPPORTS DEBUGGING

AND AUDITABILITY IN AUTOMATION PIPELINES

A script calls an API that returns HTTP 429 with a Retry-After: 30 header. Which

implementation correctly honors the server's backoff while preserving

idempotency for a POST?

A. Sleep a fixed 1s and retry the POST with the same payload up to 5 times. B. Sleep 30s, then retry the POST only if the endpoint uses an idempotency key or the request is safe to repeat. CORRECT C. Immediately retry the POST with exponential backoff starting at 100ms. D. Raise a custom exception and abandon the request to avoid duplicate side effects. RATIONALE: Retry-After specifies the server's required delay, and retrying a non-idempotent POST without an idempotency key risks duplicate side effects. Fixed or exponential backoff that ignores Retry-After violates the server's throttling contract, and abandoning the request forgoes recoverable work.

Q23 DESIGN STRUCTURED, LEVEL-APPROPRIATE LOGGING THAT SUPPORTS DEBUGGING

AND AUDITABILITY IN AUTOMATION PIPELINES

Which logging configuration best prevents sensitive API tokens from appearing in

logs while still enabling correlation of requests across modules?

A. Set the root logger to DEBUG and log the full Authorization header for traceability. B. Use a Filter on the handler that redacts Authorization headers and inject a request ID via a LoggerAdapter. CORRECT C. Log tokens only at ERROR level, since DEBUG logs are not persisted in production. D. Store tokens in a global variable and log them only when an exception is raised. RATIONALE: A handler-level Filter can redact sensitive fields regardless of log level, and a LoggerAdapter can attach a request ID for correlation without leaking secrets. Logging tokens at any level or only on exceptions still exposes credentials, and DEBUG logging increases leakage risk.

Q24 DESIGN STRUCTURED, LEVEL-APPROPRIATE LOGGING THAT SUPPORTS DEBUGGING

AND AUDITABILITY IN AUTOMATION PIPELINES

A custom exception hierarchy defines class APIError(Exception) and `class

RateLimitError(APIError). A try block catchesAPIErrorbeforeRateLimitError`.

What is the consequence?

A. RateLimitError is never caught because the parent handler shadows it. B. Python raises a SyntaxError for unreachable except clauses. C. RateLimitError is caught by the APIError handler, making the later clause unreachable. CORRECT D. Both handlers execute in order, with RateLimitError handling first. RATIONALE: Python matches except clauses top-down, so the broader APIError handler catches RateLimitError first, rendering the subclass clause unreachable. Python does not raise a SyntaxError for this ordering, and only one handler executes.

Q25 DESIGN STRUCTURED, LEVEL-APPROPRIATE LOGGING THAT SUPPORTS DEBUGGING

AND AUDITABILITY IN AUTOMATION PIPELINES

MailHog is running locally on port 1025 (SMTP) and 8025 (HTTP). A script sends

mail via smtplib but no message appears in the MailHog UI. Which cause is most

likely?

A. The script used SMTP_SSL on port 1025 instead of plain SMTP. CORRECT B. MailHog requires authentication before accepting messages. C. The script connected to port 8025 for SMTP delivery. D. MailHog discards messages without a valid MX record. RATIONALE: MailHog's SMTP listener on 1025 does not use TLS by default, so an SMTP_SSL connection fails silently or errors, preventing delivery. MailHog accepts unauthenticated mail, port 8025 is the HTTP UI, and MX records are irrelevant for local capture.

Q28 APPLY PRECISE EXCEPTION-HANDLING CONSTRUCTS (CUSTOM EXCEPTIONS,

CONTEXT MANAGERS, CHAINED EXCEPTIONS) TO PREVENT SILENT FAILURES

A script must log to both console and a rotating file, with console at INFO and file

at DEBUG, and include timestamps in ISO 8601. Which design is correct?

A. One StreamHandler at INFO; set the logger level to INFO and rely on propagation. B. Two handlers with independent levels and formatters, attached to the same logger; set logger level to DEBUG. CORRECT C. Set the root logger to DEBUG and use logging.basicConfig twice. D. Use a single FileHandler at DEBUG and print to console via print(). RATIONALE: Handlers can have independent levels and formatters, so attaching both to one logger with logger level DEBUG allows per-handler filtering. basicConfig only configures once, a single handler cannot split levels, and print bypasses logging.

Q29 APPLY PRECISE EXCEPTION-HANDLING CONSTRUCTS (CUSTOM EXCEPTIONS,

CONTEXT MANAGERS, CHAINED EXCEPTIONS) TO PREVENT SILENT FAILURES

An API client raises requests.exceptions.Timeout intermittently. Which pattern

most robustly distinguishes transient network timeouts from server-side slowness

in logs?

A. Catch Timeout and log the exception message only. B. Catch Timeout, log request URL, elapsed time, and whether the timeout was connect or read. CORRECT C. Catch Timeout and immediately retry without logging to reduce noise. D. Catch Timeout and re-raise as a generic Exception. RATIONALE: Distinguishing connect vs. read timeouts, along with URL and elapsed time, enables diagnosis of transient network issues versus server slowness. Logging only the message, suppressing logs, or collapsing to a generic Exception loses critical context.

Q30 APPLY PRECISE EXCEPTION-HANDLING CONSTRUCTS (CUSTOM EXCEPTIONS,

CONTEXT MANAGERS, CHAINED EXCEPTIONS) TO PREVENT SILENT FAILURES

A test suite uses MailHog's HTTP API at /api/v2/messages to assert that an email

was sent. Which assertion best verifies both delivery and content without race

conditions?

A. Immediately query /api/v2/messages once and assert total == 1. B. Poll /api/v2/messages with a timeout until the expected subject appears, then assert body contents. CORRECT C. Query /api/v2/messages after a fixed 5-second sleep and assert total >= 1. D. Use the SMTP server's response code as proof of delivery and skip the HTTP API. RATIONALE: Polling with a timeout avoids race conditions while confirming both delivery and content. A single immediate query or fixed sleep is flaky, total >= 1 is weak, and SMTP acceptance does not guarantee the message is queryable via the API.

Q31 APPLY PRECISE EXCEPTION-HANDLING CONSTRUCTS (CUSTOM EXCEPTIONS,

CONTEXT MANAGERS, CHAINED EXCEPTIONS) TO PREVENT SILENT FAILURES

A Python automation script calls an internal REST API using requests.Session().

Under sustained load, the script intermittently raises ConnectionError despite the

server being healthy. Which change most directly addresses connection-pool

exhaustion as the root cause?

A. Increase the requests timeout parameter to 60 seconds on every call. B. Mount an HTTPAdapter with a larger pool_maxsize and set pool_block appropriately. CORRECT C. Wrap each call in a retry loop that catches ConnectionError and sleeps 5 seconds. D. Switch from requests.Session() to a fresh requests.get() call for every request. RATIONALE: Session uses urllib3 connection pooling; pool_maxsize limits concurrent connections, and exhaustion surfaces as ConnectionError. Mounting an adapter with a larger pool (and pool_block to queue rather than drop) fixes the root cause. Timeouts address stalls, retries mask symptoms, and abandoning the session forfeits pooling entirely.

Q34 APPLY PRECISE EXCEPTION-HANDLING CONSTRUCTS (CUSTOM EXCEPTIONS,

CONTEXT MANAGERS, CHAINED EXCEPTIONS) TO PREVENT SILENT FAILURES

A script uses a try/except/finally block where the except clause raises a new

exception. Which statement about the finally block is correct?

A. The finally block is skipped because an exception is propagating. B. The finally block executes before the new exception propagates, and may suppress it if it returns. CORRECT C. The finally block executes only if the except clause completes without raising. D. The finally block executes after the new exception has fully propagated to the caller. RATIONALE: finally always runs during unwinding, before the pending exception leaves the construct. If the finally block executes a return or break, it discards the in-flight exception. It is not conditional on the except clause succeeding and runs before, not after, propagation.

Q35 APPLY PRECISE EXCEPTION-HANDLING CONSTRUCTS (CUSTOM EXCEPTIONS,

CONTEXT MANAGERS, CHAINED EXCEPTIONS) TO PREVENT SILENT FAILURES

An automation script paginates a REST API that returns a 'next' cursor in each

response. Which design most correctly handles partial failure so that a rerun does

not duplicate already-processed records?

A. Persist the last successfully processed cursor and resume from it on restart. CORRECT B. Always restart pagination from the first page and rely on idempotent writes. C. Cache all responses in memory and flush them only after the final page. D. Increase the page size to reduce the number of requests and failure windows. RATIONALE: Cursor checkpointing enables exactly-once-ish resumption after a crash without reprocessing. Restarting from the first page assumes idempotency that may not hold, in-memory caching loses state on failure, and larger pages shrink but do not eliminate the failure window.

Q36 APPLY PRECISE EXCEPTION-HANDLING CONSTRUCTS (CUSTOM EXCEPTIONS,

CONTEXT MANAGERS, CHAINED EXCEPTIONS) TO PREVENT SILENT FAILURES

A logging handler writes to a file shared by multiple processes. Records

occasionally interleave and corrupt lines. Which configuration best preserves

record integrity across processes?

A. Set the handler's formatter to include the process ID in every record. B. Use a QueueHandler with a single writer process consuming from a multiprocessing queue. CORRECT C. Open the file with mode 'a' and rely on the OS to serialize writes. D. Reduce the logging level to WARNING to lower write frequency. RATIONALE: QueueHandler funnels records to one consumer process that owns the file, eliminating concurrent writes and interleaving. Including PIDs aids debugging but not atomicity, append mode does not guarantee atomic multi-write records, and lowering verbosity only reduces, not removes, contention.

Q37 INTEGRATE API, EMAIL, LOGGING, AND EXCEPTION COMPONENTS INTO A COHESIVE,

TESTABLE AUTOMATION SOLUTION

A custom exception class is defined as class ConfigError(Exception): pass. A

caller writes except Exception as e: but also wants to distinguish ConfigError for a

specific remediation. Which practice best supports this without losing the original

traceback?

A. Catch ConfigError in a dedicated except clause before the general Exception clause. CORRECT B. Inspect e.class.name inside the general handler and branch on the string. C. Re-raise with raise ConfigError(str(e)) inside the general handler. D. Use a bare except and check isinstance(e, ConfigError) after assignment. RATIONALE: Ordering a specific except before the general one lets Python route ConfigError appropriately while preserving context and traceback. String-name branching is fragile, re-raising a new exception discards the original traceback (unless 'from' is used), and a bare except cannot bind e.