How do syntax errors differ from exceptions?
A syntax error prevents Python from parsing code, whereas an exception occurs while syntactically valid code is running.
Study 7 Exceptions and Error Handling with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
How do syntax errors differ from exceptions?
A syntax error prevents Python from parsing code, whereas an exception occurs while syntactically valid code is running.
How should a Python traceback be read?
Read a traceback from the bottom upward: its final line gives the exception type and message, while preceding lines show the call path.
When does Python raise `ValueError`?
`ValueError` means the value has an acceptable general type but invalid content, as with `int("abc")`.
When does Python raise `TypeError`?
`TypeError` means an operation received an inappropriate type, such as adding the string `"total"` to the integer `3`.
What is the control flow of `try` and `except`?
`try` contains the operation that may fail; if a matching exception occurs, the remaining `try` statements are skipped and the corresponding `except` handler runs.
What should exception handlers generally catch?
Catch specific exceptions whenever possible, so expected failures are handled without hiding unrelated programming errors.
When does a `try` statement’s `else` clause run?
An `else` clause runs only when the `try` block succeeds without raising an exception.
What is the purpose of `finally`?
A `finally` clause runs whether or not an exception occurs, making it suitable for cleanup such as releasing resources or restoring state.
Why use `with` for resource management?
Prefer `with` for files and other context managers because it performs normal cleanup automatically, including when an exception occurs inside the block.
When should code use `raise`?
Use `raise` when a function cannot fulfill its contract or an input violates a required rule; for example, reject a percentage outside the range 0 through 100.
How can a handler re-raise the current exception?
Inside an `except` block, a bare `raise` re-raises the currently handled exception while preserving its traceback.
What does `from error` provide in exception chaining?
Exception chaining with `from error` translates a low-level failure into a clearer application-level exception while recording the original cause.