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?
import
def
except
while
7 Which optional block runs whether or not an exception occurs?
raise
finally
except
else
8
When does the else block of a try statement execute?
finally block
try block
9 Which built-in class is normally used as the base class for a user-defined exception?
list
Exception
str
object
10 Which keyword is used to trigger an exception intentionally?
raise
assert
except
return
11
Which statement correctly defines a custom exception named AgeError?
class AgeError(Exception): pass
raise AgeError(Exception): pass
def AgeError(Exception): pass
except AgeError(Exception): pass
12
How can a custom exception named AgeError be triggered?
except AgeError()
return AgeError()
raise AgeError()
import AgeError()
13 Which file mode opens a text file for reading?
"w"
"r"
"x"
"a"
14 Which file mode writes to a file and replaces its existing content?
"r"
"a"
"x"
"w"
15 Which method reads the entire contents of a text file?
seek()
close()
write()
read()
16 Which file method adds a string to an open text file?
write()
read()
flush()
tell()
17 Which standard Python module is commonly used to work with JSON data?
random
json
math
csv
18 Which function reads JSON data from an open file object?
json.load()
json.loads()
json.dump()
json.dumps()
19 Which function converts a JSON-formatted string into a Python object?
json.dump()
json.loads()
json.dumps()
json.load()
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")
ArithmeticError
TypeError
ValueError
ZeroDivisionError
22
What exception is raised when the following code is executed?
values = {"a": 10}
print(values["b"])
ValueError
KeyError
NameError
IndexError
23
What exception will int("12.5") raise?
OverflowError
IndexError
TypeError
ValueError
24
Which exception is raised by items[5] when items = [10, 20, 30]?
ValueError
IndexError
LookupError
KeyError
25
What is printed by the following code?
try:
value = int("abc")
except ValueError:
print("Invalid")
else:
print("Valid")
Invalid
Valid
Invalid followed by Valid
26 Which ordering of exception handlers correctly allows both exceptions to be handled separately?
except ValueError before except Exception
except Exception before except ValueError
except ArithmeticError before except ZeroDivisionError
except BaseException before except TypeError
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?
exception InvalidAgeError(Exception): pass
class InvalidAgeError: raise Exception
def InvalidAgeError(Exception): pass
class InvalidAgeError(Exception): pass
30
Assume InsufficientFundsError is a valid exception class. Which statement raises it with a useful message?
except InsufficientFundsError("Balance too low")
throw InsufficientFundsError("Balance too low")
return InsufficientFundsError("Balance too low")
raise InsufficientFundsError("Balance too low")
31
Given class NegativeNumberError(Exception): pass, which handler catches that exception specifically?
except ValueError only:
except NegativeNumberError:
catch NegativeNumberError:
except raise NegativeNumberError:
32
A function must reject scores outside the range using InvalidScoreError. Which condition is correct?
if score < 0 or score > 100: raise InvalidScoreError()
if 0 < score < 100: raise InvalidScoreError()
if score == 0 or score == 100: raise InvalidScoreError()
if score < 0 and score > 100: raise InvalidScoreError()
33 Which file mode appends text to an existing file without removing its current contents?
"x"
"w"
"a"
"r"
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()
readline()
readlines()
read()
36 After reading a file to its end, which operation moves the file cursor back to the beginning?
file.seek(0)
file.read(0)
file.reset(0)
file.tell(0)
37
What does file.write("Python") normally return when writing to a text file succeeds?
6
True
None
"Python"
38
Which code correctly reads and parses JSON data from an already opened file object named file?
data = json.load(file)
data = json.loads(file)
data = json.read(file)
data = file.json()
39
A JSON file contains {"active": true, "score": null}. After json.load(), which Python values are stored for active and score?
true and null
"true" and "null"
True and None
1 and 0
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)
UnboundLocalError.
NameError.
outer.
42
What value is returned by f()?
def f():
try:
return 1 / 0
except ZeroDivisionError:
return "except"
finally:
return "finally"
ZeroDivisionError escapes.
"finally"
"except"
None
43
What is the outcome of this code?
try:
value = int("5")
except ValueError:
print("conversion failed")
else:
raise ValueError("later failure")
else clause is skipped completely.
except clause handles the later failure.
ValueError propagates uncaught.
conversion failed.
44
Which exception is not caught by the handler below under Python's standard exception hierarchy?
try:
operation()
except Exception:
recover()
RuntimeError
UnicodeError
ArithmeticError
KeyboardInterrupt
45
What does this code print?
try:
try:
1 / 0
except ZeroDivisionError:
raise ValueError("invalid")
except ValueError as err:
print(type(err.__context__).__name__)
ZeroDivisionError
Exception
ValueError
NoneType
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")
A.
CombinedError uncaught.
B.
A and B.
47
What exception actually results from executing raise CodeError?
class CodeError(Exception):
def __init__(self, code):
super().__init__(f"code={code}")
TypeError caused by missing code
CodeError containing the class name
RuntimeError caused by invalid raising
CodeError with an empty message
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.__context__ is always set to None.
result.__cause__ is the WrappedError itself.
result.__cause__ is the original ValueError.
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)
(0, "abc", 0)
(3, "abc", 3)
(3, "", 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 "XYdef".
data is "abc"; content is "XYabcdef".
data is "def"; content is "abcdefXY".
data is "cde"; content is "XYcdef".
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()
"Xbc"
"Xabc"
"abcX"
"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
4, the number of Unicode units
3, the number of characters
7, the number of UTF-8 bytes
54
What exact text is written by this code?
with open(path, "w") as file:
file.writelines(["a", "b\n", "c"])
"a b\n c"
"ab\nc"
"abc\n"
"a\nb\nc\n"
55
According to Python's standard json module behavior, what value is produced by json.loads('{"x": 1, "x": 2}')?
{"x": [1, 2]}
{"x": 2}
JSONDecodeError
{"x": 1}
56
What is assigned to result?
result = json.loads(
'{"x": 1}',
object_hook=lambda obj: "OBJECT",
object_pairs_hook=lambda pairs: "PAIRS"
)
"PAIRS"
{"x": 1}
TypeError
"OBJECT"
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, 100.0]
["10", "2.5", "1e2"]
58
What happens when this expression is evaluated, where the Python string starts with a Unicode BOM?
json.loads("\ufeff{\"x\": 1}")
{"x": 1}.
JSONDecodeError.
{"x": 1}.
UnicodeDecodeError.
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)
second receives an empty dictionary.
EOFError.
{"x": 1}.
JSONDecodeError.
60
What is the value of restored?
original = {1: "integer", "1": "string"}
restored = json.loads(json.dumps(original))
{1: "integer", "1": "string"}
{"1": "string"}
TypeError is raised.
{"1": "integer"}
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 →