These questions ask you to read a failure display, choose the exception family that fits an operation, or follow a try statement. Begin with the failed operation rather than guessing from the wording of its message.
Read the phase, path and category
First decide whether Python could parse the code. A SyntaxError stops the affected code before execution, and its marker is a clue that may appear after the real mistake. If execution began, read ordinary traceback frames from the outermost reported call towards the most recent frame. The concluding line begins with the exception category and then gives diagnostic detail.
| Failed operation | Usual category |
|---|---|
| Resolve a name with no binding in any applicable scope, as in total = missing + 2 | NameError |
| Use an unsuitable type or argument shape, as in "a" - 1 | TypeError |
| Use an allowed type whose content is unsuitable, as in int("blue") | ValueError |
| Read a sequence position outside its range, as in "sun"[8] | IndexError |
| Request an absent mapping entry, as in dict(a=2)["z"] | KeyError |
| Request an attribute the object lacks, as in "sun".push(2) | AttributeError |
| Divide, floor-divide or take a remainder with numeric zero, as in 8 // 0 | ZeroDivisionError |
For handling, compare classes rather than message text. A clause naming one exception class also catches instances of its subclasses raised from the associated try suite. Follow the branches separately: except handles a match, else runs only when the try suite raises nothing, and finally runs as control leaves the statement whether execution succeeded or failed.
Reject these tempting routes
| Tempting route | How to reject it |
|---|---|
| Read the first frame as the failure site or search there for the category | Follow the call chain down to the most recent frame, then read the category at the start of the concluding line. |
| Use NameError for an absent mapping entry, or KeyError for an unresolved variable | Ask what lookup occurred: scope lookup concerns a name; subscription concerns a mapping entry. |
| Choose TypeError whenever a value is unusable | Separate unsuitable type or shape from unsuitable content inside an allowed type. The latter commonly produces ValueError. |
| Expect an excessive direct sequence position to clip or return None | Direct indexing needs one valid position and raises IndexError outside the range. Clipping belongs to slicing. |
| Treat a missing method as an undefined name | The receiver exists; attribute lookup on that object failed, so AttributeError fits the operation. |
| Turn a zero divisor into infinity, zero or a remainder | All three numeric division forms reject a zero divisor with ZeroDivisionError. |
Try it
Classify SyntaxError diagnostics when Python cannot parse a piece of code. Which statements are true? Select all that apply.
- The affected code is rejected before it executes.
- Only malformed arithmetic can cause it.
- The indicated location may follow the real mistake.
- The marker always identifies the exact character to change.
Classify matching when an except clause names an exception class. Which statements are true? Select all that apply.
- The diagnostic message text determines the match.
- Only an instance of the exact named class can match.
- An instance of the named class can match.
- An instance of a subclass can also match.
Which statement correctly distinguishes else and finally in a try statement?
- Else needs an exception-free try; finally runs on either outcome.
- Else handles exceptions that no except clause matches.
- Finally runs only when an exception occurs.
- Else and finally have interchangeable conditions.