Exceptions & Files questions and answers
try/except/else/finally, raising errors and the with statement. Practise exceptions & files questions from the python section of placement tests, with a worked explanation after every answer. Practice is free and needs no sign-up.
Sample exceptions & files questions with worked answers
Question 1
In a try statement, when does the code inside the finally block run?
- Always, whether or not an exception was raised in the try block
- Only when the try block raises an exception
- Only when the try block finishes without an exception
- Only when no except clause matches the exception
Answer: A. Always, whether or not an exception was raised in the try block
Explanation: finally is meant for clean-up such as closing a file, so Python runs it on every path out of the try statement: normal completion, a handled exception or an unhandled one.
Question 2
Why is with open("data.txt") as f: preferred over calling open() and close() separately?
- The file is read faster because with loads it fully into memory
- Any exception raised inside the block is silently ignored
- The file is closed automatically when the block ends, even if an exception occurs inside it
- The file is created automatically if it does not exist
Answer: C. The file is closed automatically when the block ends, even if an exception occurs inside it
Explanation: The with statement calls the file's clean-up code on every exit from the block, including when an error is raised. It does not hide the error or change how the file is opened.
Question 3
Which of these exceptions is NOT caught by a handler written as except Exception:?
- ZeroDivisionError
- KeyError
- KeyboardInterrupt
- FileNotFoundError
Answer: C. KeyboardInterrupt
Explanation: KeyboardInterrupt derives directly from BaseException, not from Exception, so that Ctrl+C is not swallowed by ordinary handlers. The other three are all subclasses of Exception.
All 20 exceptions & files questions with answers
- A division by zero happens inside a try block that has a matching except…
- Which exception does Python raise when int() is given text that is not a whole…
- In a try statement, when does the code inside the finally block run?
- A dictionary of marks is asked for a name that was never stored. Which…
- A file report.txt already has some text in it. What happens to that text when…
- The try block below completes without any error and the statement has an else…
- io.StringIO lets a string be read like a text file. How many lines does…
- A try statement has except, else and finally clauses, and an error occurs in…
- An out-of-range list index is handled by two except clauses, the first naming…
- A custom exception carries a message built inside withdraw. What does printing…
- Lines of numbers are read from a file-like object inside a with block and…
- read() is called three times on the same file-like object, first with a size…
- Why is with open("data.txt") as f: preferred over calling open() and close()…
- The only except clause below names TypeError, but the conversion fails in a…
- readline() is called twice and then read() once on a three-line file-like…
- A function returns from inside try, and its finally block has a print. In what…
- All three parts of this try statement contain a return. What does risky() give…
- parse() catches one exception and raises a different one from its handler…
- Which of these exceptions is NOT caught by a handler written as except…
- Two lines are written to an in-memory text file, which is read once before and…
Exceptions & Files: common questions
What are exceptions & files questions?
try/except/else/finally, raising errors and the with statement. They appear in the python section of many placement tests.
Where can I practise exceptions & files questions with answers for free?
Right here on LogicWiz Exams. Every exceptions & files question has a worked explanation after you answer. Practice is free and needs no sign-up.
How should I practise exceptions & files?
Start with easy questions, then move to medium and hard. Read the explanation after each answer, and come back to the ones you missed.
Start practising
On this page you can start a fresh set of exceptions & files questions, choose easy, medium or hard, and time yourself if you want to. Or practise the whole subject: Python practice.
More python topics
- Variables, Types & Operators: Dynamic typing, numbers, operators, precedence and truthiness.
- Python Strings: Indexing, slicing, methods, formatting and immutability.
- Lists & Tuples: Slicing, methods, copies, sorting and unpacking.
- Dictionaries & Sets: Lookups, iteration, hashable keys and set operations.
- Conditions & Loops: if/elif, for, while, range, break, continue and loop else.
- Functions & Scope: Arguments, defaults, *args, closures, lambda and recursion.
- Comprehensions & Generators: List, dict and set comprehensions, yield and lazy evaluation.
- Classes & Objects: Attributes, inheritance, super(), dunder methods and properties.
- Built-ins & Standard Library: sorted, zip, any/all, collections, itertools and imports.
Other subjects
- Quantitative Aptitude: Arithmetic, percentages, time and work, speed, probability and data interpretation: the numerical section of every fresher test.
- Logical Reasoning: Series, coding-decoding, arrangements, syllogisms and puzzles: the section that separates prepared candidates from the rest.
- Verbal Ability: Vocabulary, grammar, reading comprehension and sentence order: tested in nearly every IT services hiring exam.
- Technical & Programming: CS fundamentals, output prediction and pseudo-code: the technical MCQ round for IT roles.
- SQL: SQL quizzes by topic, from SELECT and joins to window functions: query output and concepts for analyst and developer roles.
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge · Test from a job description · LogicWiz Open: free team quiz · Free interview prep