QuestenaPractice that shows what to review next
Topic lesson

Errors and exceptions: locate the failed operation first

About 5 min

Questions stay in the language in which they were published.

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 operationUsual category
Resolve a name with no binding in any applicable scope, as in total = missing + 2NameError
Use an unsuitable type or argument shape, as in "a" - 1TypeError
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 // 0ZeroDivisionError

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 routeHow to reject it
Read the first frame as the failure site or search there for the categoryFollow 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 variableAsk what lookup occurred: scope lookup concerns a name; subscription concerns a mapping entry.
Choose TypeError whenever a value is unusableSeparate 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 NoneDirect indexing needs one valid position and raises IndexError outside the range. Clipping belongs to slicing.
Treat a missing method as an undefined nameThe receiver exists; attribute lookup on that object failed, so AttributeError fits the operation.
Turn a zero divisor into infinity, zero or a remainderAll three numeric division forms reject a zero divisor with ZeroDivisionError.

Try it

Question 85

Classify SyntaxError diagnostics when Python cannot parse a piece of code. Which statements are true? Select all that apply.

  1. The affected code is rejected before it executes.
  2. Only malformed arithmetic can cause it.
  3. The indicated location may follow the real mistake.
  4. The marker always identifies the exact character to change.
Question 95

Classify matching when an except clause names an exception class. Which statements are true? Select all that apply.

  1. The diagnostic message text determines the match.
  2. Only an instance of the exact named class can match.
  3. An instance of the named class can match.
  4. An instance of a subclass can also match.
Question 96

Which statement correctly distinguishes else and finally in a try statement?

  1. Else needs an exception-free try; finally runs on either outcome.
  2. Else handles exceptions that no except clause matches.
  3. Finally runs only when an exception occurs.
  4. Else and finally have interchangeable conditions.
Start drillPractice this topic
Errors and exceptions: locate the failed operation first · Questena