Unit 3: File Handling and Exception Handling - Practice Quiz
1 Which built-in exception occurs when a number is divided by zero?
2
Which exception is commonly raised by int("hello")?
3 Which exception occurs when an undefined variable is used?
4 Which exception is raised when a list index is outside the valid range?
5
What is the main purpose of a try block?
6
Which block handles an exception raised inside a try block?
while
import
def
except
7 Which optional block runs whether or not an exception occurs?
else
raise
finally
except
8
When does the else block of a try statement execute?
try block
finally block
9 Which built-in class is normally used as the base class for a user-defined exception?
object
str
list
Exception
10 Which keyword is used to trigger an exception intentionally?
assert
return
except
raise
11
Which statement correctly defines a custom exception named AgeError?
except AgeError(Exception): pass
def AgeError(Exception): pass
raise AgeError(Exception): pass
class AgeError(Exception): pass
12
How can a custom exception named AgeError be triggered?
raise AgeError()
import AgeError()
return AgeError()
except AgeError()
13 Which file mode opens a text file for reading?
"x"
"a"
"w"
"r"
14 Which file mode writes to a file and replaces its existing content?
"r"
"w"
"x"
"a"
15 Which method reads the entire contents of a text file?
write()
seek()
read()
close()
16 Which file method adds a string to an open text file?
write()
flush()
read()
tell()
17 Which standard Python module is commonly used to work with JSON data?
random
csv
json
math
18 Which function reads JSON data from an open file object?
json.load()
json.dump()
json.dumps()
json.loads()
19 Which function converts a JSON-formatted string into a Python object?
json.load()
json.dumps()
json.dump()
json.loads()
20 A JSON object is usually converted into which Python data type?
21
What exception is raised by the following code?
result = 15 / int("0")
ValueError
ArithmeticError
TypeError
ZeroDivisionError
22
What exception is raised when the following code is executed?
values = {"a": 10}
print(values["b"])
ValueError
NameError
KeyError
IndexError
23
What exception will int("12.5") raise?
TypeError
ValueError
OverflowError
IndexError
24
Which exception is raised by items[5] when items = [10, 20, 30]?
LookupError
ValueError
KeyError
IndexError
25
What is printed by the following code?
try:
value = int("abc")
except ValueError:
print("Invalid")
else:
print("Valid")
Valid
Invalid
Invalid followed by Valid
26 Which ordering of exception handlers correctly allows both exceptions to be handled separately?
except BaseException before except TypeError
except ValueError before except Exception
except Exception before except ValueError
except ArithmeticError before except ZeroDivisionError
27
In a try statement, when is the else block executed?
try block raises no exception
finally block is skipped
except block finishes
28
What is the main purpose of a finally block?
try block automatically
29
Which definition correctly creates a user-defined exception named InvalidAgeError?
class InvalidAgeError: raise Exception
def InvalidAgeError(Exception): pass
class InvalidAgeError(Exception): pass
exception InvalidAgeError(Exception): pass
30
Assume InsufficientFundsError is a valid exception class. Which statement raises it with a useful message?
raise InsufficientFundsError("Balance too low")
return InsufficientFundsError("Balance too low")
throw InsufficientFundsError("Balance too low")
except InsufficientFundsError("Balance too low")
31
Given class NegativeNumberError(Exception): pass, which handler catches that exception specifically?
except ValueError only:
except NegativeNumberError:
except raise NegativeNumberError:
catch NegativeNumberError:
32
A function must reject scores outside the range using InvalidScoreError. Which condition is correct?
if score < 0 and score > 100: raise InvalidScoreError()
if score < 0 or score > 100: raise InvalidScoreError()
if score == 0 or score == 100: raise InvalidScoreError()
if 0 < score < 100: raise InvalidScoreError()
33 Which file mode appends text to an existing file without removing its current contents?
"r"
"a"
"w"
"x"
34
What is an important benefit of using with open("notes.txt", "r") as file:?
35 Which method reads all remaining lines of a text file and returns them as a list of strings?
write()
readlines()
read()
readline()
36 After reading a file to its end, which operation moves the file cursor back to the beginning?
file.read(0)
file.seek(0)
file.reset(0)
file.tell(0)
37
What does file.write("Python") normally return when writing to a text file succeeds?
True
None
6
"Python"
38
Which code correctly reads and parses JSON data from an already opened file object named file?
data = json.load(file)
data = json.read(file)
data = file.json()
data = json.loads(file)
39
A JSON file contains {"active": true, "score": null}. After json.load(), which Python values are stored for active and score?
"true" and "null"
1 and 0
True and None
true and null
40 Which exception should be handled when a JSON file is opened successfully but contains malformed JSON syntax?
json.JSONDecodeError
FileNotFoundError
PermissionError
UnicodeEncodeError
41
What happens when the following code is executed?
e = "outer"
try:
1 / 0
except ZeroDivisionError as e:
pass
print(e)
outer.
NameError.
UnboundLocalError.
42
What value is returned by f()?
def f():
try:
return 1 / 0
except ZeroDivisionError:
return "except"
finally:
return "finally"
"except"
"finally"
ZeroDivisionError escapes.
None
43
What is the outcome of this code?
try:
value = int("5")
except ValueError:
print("conversion failed")
else:
raise ValueError("later failure")
except clause handles the later failure.
else clause is skipped completely.
conversion failed.
ValueError propagates uncaught.
44
Which exception is not caught by the handler below under Python's standard exception hierarchy?
try:
operation()
except Exception:
recover()
RuntimeError
UnicodeError
KeyboardInterrupt
ArithmeticError
45
What does this code print?
try:
try:
1 / 0
except ZeroDivisionError:
raise ValueError("invalid")
except ValueError as err:
print(type(err.__context__).__name__)
ValueError
ZeroDivisionError
NoneType
Exception
46
What does the following code print?
class AError(Exception):
pass
class BError(Exception):
pass
class CombinedError(AError, BError):
pass
try:
raise CombinedError()
except BError:
print("B")
except AError:
print("A")
B.
A.
A and B.
CombinedError uncaught.
47
What exception actually results from executing raise CodeError?
class CodeError(Exception):
def __init__(self, code):
super().__init__(f"code={code}")
CodeError containing the class name
RuntimeError caused by invalid raising
CodeError with an empty message
TypeError caused by missing code
48
What is the value of (err.args, str(err), err.field)?
class ValidationError(Exception):
def __init__(self, field):
self.field = field
super().__init__(field.upper())
err = ValidationError("age")
((), "AGE", "age")
(("AGE",), "age", "AGE")
(("age",), "age", "AGE")
(("AGE",), "AGE", "age")
49
After the outer handler catches WrappedError, which statement is true?
class WrappedError(Exception):
pass
try:
try:
int("x")
except ValueError as original:
raise WrappedError("wrapped") from original
except WrappedError as err:
result = err
result.__cause__ is the WrappedError itself.
result.__cause__ is the original ValueError.
result.__context__ is always set to None.
result.__suppress_context__ is set to False.
50
Assume path can be opened normally. What is (n, data, position) after this code?
with open(path, "w+") as file:
n = file.write("abc")
data = file.read()
position = file.tell()
(3, "", 3)
(3, "abc", 3)
(3, "", 0)
(0, "abc", 0)
51
A text file initially contains abcdef. What are data and the final file content after this code?
with open(path, "r+") as file:
file.write("XY")
data = file.read(3)
data is "cde"; content is "XYcdef".
data is "abc"; content is "XYabcdef".
data is "cde"; content is "XYdef".
data is "def"; content is "abcdefXY".
52
A text file initially contains abc. What does content become?
with open(path, "a+") as file:
file.seek(0)
file.write("X")
file.seek(0)
content = file.read()
"abcX"
"Xabc"
"Xbc"
"abc"
53
Under UTF-8 encoding, what value does count normally receive?
with open(path, "w", encoding="utf-8") as file:
count = file.write("Aé𝄞")
8, including an implicit terminator
7, the number of UTF-8 bytes
4, the number of Unicode units
3, the number of characters
54
What exact text is written by this code?
with open(path, "w") as file:
file.writelines(["a", "b\n", "c"])
"abc\n"
"ab\nc"
"a\nb\nc\n"
"a b\n c"
55
According to Python's standard json module behavior, what value is produced by json.loads('{"x": 1, "x": 2}')?
{"x": 1}
JSONDecodeError
{"x": [1, 2]}
{"x": 2}
56
What is assigned to result?
result = json.loads(
'{"x": 1}',
object_hook=lambda obj: "OBJECT",
object_pairs_hook=lambda pairs: "PAIRS"
)
{"x": 1}
"OBJECT"
"PAIRS"
TypeError
57
What value is returned by the following call?
json.loads('[10, 2.5, 1e2]', parse_int=str)
["10", 2.5, "1e2"]
["10", 2.5, 100.0]
["10", "2.5", "1e2"]
[10, 2.5, 100.0]
58
What happens when this expression is evaluated, where the Python string starts with a Unicode BOM?
json.loads("\ufeff{\"x\": 1}")
UnicodeDecodeError.
JSONDecodeError.
{"x": 1}.
{"x": 1}.
59
A file contains exactly {"x": 1}. What happens in this code?
with open(path, encoding="utf-8") as file:
first = json.load(file)
second = json.load(file)
{"x": 1}.
EOFError.
JSONDecodeError.
second receives an empty dictionary.
60
What is the value of restored?
original = {1: "integer", "1": "string"}
restored = json.loads(json.dumps(original))
{"1": "integer"}
{1: "integer", "1": "string"}
{"1": "string"}
TypeError is raised.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →