File I/O and Exception Handling Flashcards
7 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 File I/O and Exception Handling flashcards as text
What is the correct way to raise a custom exception with a message in Python?
Answer: raise Exception('msg')
In Python, you use `raise ExceptionClass(args)` to raise an exception with a message.
Given `with open('data.txt', 'w') as f: f.write('hello')`, what is the state of the file after the `with` block exits normally?
Answer: The file is closed and contains 'hello'
Exiting a `with` block calls `__exit__`, which flushes the write buffer and closes the file, so 'hello' is persisted.
Which exception class should a custom exception inherit from to be considered a user-defined application error?
Answer: Exception
Custom exceptions should inherit from `Exception` (not `BaseException`) so they don't accidentally catch system-exit signals.
What does the `truncate(size)` method do when called on a writable file object?
Answer: Resizes the file to at most `size` bytes
`truncate(size)` resizes the file so it is at most `size` bytes, padding with null bytes if size is larger than the current file.
What will the following code print? ```python try: raise ValueError('oops') except TypeError: print('type') except ValueError: print('value') ```
Answer: value
The `ValueError` exception matches the second `except` clause, so 'value' is printed.
When writing to a file opened with mode `'a'`, where does the write pointer start?
Answer: At the end of the file
Append mode (`'a'`) always writes at the end of the file, even if `seek()` was called beforehand.
Which statement about exception chaining using `raise NewError() from original_error` is correct?
Answer: It stores the original exception in `__cause__` and sets `__suppress_context__` to True
`raise X from Y` sets `X.__cause__ = Y` and `X.__suppress_context__ = True`, making the chain explicit in tracebacks.