The correct construct for handling runtime failures (for example, login failures, network timeouts, or server errors) in Python is a try/except block (option C). Wrapping potentially failing operations in a try block and handling exceptions in except allows the script to catch the exception and continue execution (log the error, skip the target, retry, etc.) rather than crashing.
Why C is correct:
try/except is the Python mechanism to handle exceptions raised during execution. For network/email operations (IMAP login/select), IMAP libraries raise exceptions on failure — try/except catches these and enables recovery logic.
Example corrected snippet:
import imaplib, sys
def enumerate_inbox(server, port, user, passwd):
try:
mail = imaplib.IMAP4(server, port)
mail.login(user, passwd)
status, messages = mail.select( " inbox " )
print(f " Total Emails: {int(messages[0])} " )
except imaplib.IMAP4.error as e:
print(f " IMAP error for {user}: {e} " )
# continue to next account or retry
except Exception as e:
print(f " Unexpected error for {user}: {e} " )
finally:
try:
mail.logout()
except:
pass
Why the other options are not the best fit:
A. do/while loop: Python has no native do/while; loops alone won’t catch exceptions — they may repeat the crash.
B. iterator: Iterators control iteration over collections, not exception handling.
D. if/else conditional: Conditionals can test return values but cannot handle exceptions thrown by library calls; they are not sufficient to prevent the script from aborting when an exception is raised.
CompTIA PT0-003 Mapping:
Domain 4.0 Tools and Code Analysis — basic defensive programming and error handling when writing or reviewing scripts used in engagements (use exception handling to make enumeration tools robust and predictable).