PCEP-30-02 practice question 29 of 35

What optional clauses does a try ... except ... statement have? (select 2)

Full set: 548 questions

Domain Functions and Exceptions

Answer options
A: after
B: before
C: else Correct answer
D: finally Correct answer
Correct Answer:
C. else; D. finally
Explanation

The try...except statement in Python is used for handling exceptions. It can be extended with two optional clauses: else and finally. The else clause is executed if and only if the try block completes without raising an exception. It is useful for code that should run when no errors occur. The finally clause is always executed before leaving the try statement, regardless of whether an exception was raised or not. This makes it ideal for cleanup actions, such as closing files or network connections, that must be performed under all circumstances.

Why Incorrect

A. after: after is not a valid keyword or clause within Python's exception handling syntax.
B. before: before is not a valid keyword or clause within Python's exception handling syntax.

References

1. Python Software Foundation. (2023). The Python Tutorial, Section 8.3: Handling Exceptions. The official tutorial explains the try...except statement and its optional clauses. It states, "The try ... except statement has an optional else clause..."

2. Python Software Foundation. (2023). The Python Tutorial, Section 8.6: Defining Clean-up Actions. This section is dedicated to the finally clause, stating, "The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances."

3. Python Software Foundation. (2023). The Python Language Reference, Section 8.4: The try statement. This document provides the formal grammar for the try statement, explicitly showing else and finally as optional components of the syntax.

4. Guttag, J. V. (2016). Introduction to Computation and Programming Using Python, With Application to Understanding Data (2nd ed.). MIT Press. Chapter 10, "An Introduction to Classes," discusses exception handling, including the use of try, except, else, and finally blocks (Section 10.1, page 178).

5. MIT OpenCourseWare. (2016). 6.0001 Introduction to Computer Science and Programming in Python, Lecture 10: Exceptions. The lecture notes and code examples demonstrate the full structure of exception handling, including the optional else and finally blocks.

Scroll to Top