How does a syntax error differ from an exception?
A syntax error prevents Python from parsing a program; an exception occurs while syntactically valid code is executing.
Study 8 Exceptions and Error Handling with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
How does a syntax error differ from an exception?
A syntax error prevents Python from parsing a program; an exception occurs while syntactically valid code is executing.
What happens when an exception occurs in a try block?
Python runs the try block, skips the rest if an exception occurs, and searches for a matching except clause. If none matches, the exception propagates outward.
Why catch specific exception types?
Use specific handlers such as FileNotFoundError or PermissionError so each expected failure receives an appropriate response.
When does an else block run in exception handling?
The else block runs only when the try block completes without raising an exception.
What is the purpose of finally?
A finally block runs whether or not an exception occurs, making it suitable for cleanup such as closing resources or releasing locks.
Why prefer with for opening files?
The with statement automatically closes a file, including when an exception occurs, so it is usually preferable for file resources.
When should a function use raise?
Use raise when a function detects an invalid condition and its caller should decide how to respond.
What does a bare raise do in an except block?
A bare raise sends the current exception onward while preserving its traceback, allowing local logging without claiming the failure was handled.
What is the purpose of exception chaining?
raise ... from ... preserves the original low-level exception as the explicit cause of a higher-level exception.
What should a custom exception normally inherit from?
A user-defined exception normally inherits from Exception, allowing callers to handle a meaningful application-specific error.
Where should input validation occur?
Validate data at program boundaries, such as when input enters the program, so invalid values are rejected early and clearly.
When should code catch an exception?
Catch an exception only when the function can take useful action, such as retrying, requesting new input, supplying a default, or translating the error.