Unit 3: File Handling and Exception Handling - Practice Quiz

CAP776 — Programming In Python 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which built-in exception occurs when a number is divided by zero?

Built-in exceptions Easy
A. TypeError
B. ValueError
C. ZeroDivisionError
D. IndexError

2 Which exception is commonly raised by int("hello")?

Built-in exceptions Easy
A. KeyError
B. ValueError
C. NameError
D. TypeError

3 Which exception occurs when an undefined variable is used?

Built-in exceptions Easy
A. IndexError
B. NameError
C. KeyError
D. OSError

4 Which exception is raised when a list index is outside the valid range?

Built-in exceptions Easy
A. IndexError
B. TypeError
C. ValueError
D. KeyError

5 What is the main purpose of a try block?

Try and except Easy
A. To test risky code
B. To import a module
C. To repeat a statement
D. To define a function

6 Which block handles an exception raised inside a try block?

Try and except Easy
A. while
B. import
C. def
D. except

7 Which optional block runs whether or not an exception occurs?

Try and except Easy
A. else
B. raise
C. finally
D. except

8 When does the else block of a try statement execute?

Try and except Easy
A. When any exception occurs
B. Before the try block
C. When no exception occurs
D. After the finally block

9 Which built-in class is normally used as the base class for a user-defined exception?

User-defined exceptions Easy
A. object
B. str
C. list
D. Exception

10 Which keyword is used to trigger an exception intentionally?

User-defined exceptions Easy
A. assert
B. return
C. except
D. raise

11 Which statement correctly defines a custom exception named AgeError?

User-defined exceptions Easy
A. except AgeError(Exception): pass
B. def AgeError(Exception): pass
C. raise AgeError(Exception): pass
D. class AgeError(Exception): pass

12 How can a custom exception named AgeError be triggered?

User-defined exceptions Easy
A. raise AgeError()
B. import AgeError()
C. return AgeError()
D. except AgeError()

13 Which file mode opens a text file for reading?

Text file read/write operations Easy
A. "x"
B. "a"
C. "w"
D. "r"

14 Which file mode writes to a file and replaces its existing content?

Text file read/write operations Easy
A. "r"
B. "w"
C. "x"
D. "a"

15 Which method reads the entire contents of a text file?

Text file read/write operations Easy
A. write()
B. seek()
C. read()
D. close()

16 Which file method adds a string to an open text file?

Text file read/write operations Easy
A. write()
B. flush()
C. read()
D. tell()

17 Which standard Python module is commonly used to work with JSON data?

Reading JSON files Easy
A. random
B. csv
C. json
D. math

18 Which function reads JSON data from an open file object?

Reading JSON files Easy
A. json.load()
B. json.dump()
C. json.dumps()
D. json.loads()

19 Which function converts a JSON-formatted string into a Python object?

Reading JSON files Easy
A. json.load()
B. json.dumps()
C. json.dump()
D. json.loads()

20 A JSON object is usually converted into which Python data type?

Reading JSON files Easy
A. Tuple
B. Set
C. Dictionary
D. Complex number

21 What exception is raised by the following code?

result = 15 / int("0")

Built-in exceptions Medium
A. ValueError
B. ArithmeticError
C. TypeError
D. ZeroDivisionError

22 What exception is raised when the following code is executed?

values = {"a": 10}

print(values["b"])

Built-in exceptions Medium
A. ValueError
B. NameError
C. KeyError
D. IndexError

23 What exception will int("12.5") raise?

Built-in exceptions Medium
A. TypeError
B. ValueError
C. OverflowError
D. IndexError

24 Which exception is raised by items[5] when items = [10, 20, 30]?

Built-in exceptions Medium
A. LookupError
B. ValueError
C. KeyError
D. IndexError

25 What is printed by the following code?

try:

value = int("abc")

except ValueError:

print("Invalid")

else:

print("Valid")

Try and except Medium
A. Valid
B. Nothing is printed
C. Invalid
D. Invalid followed by Valid

26 Which ordering of exception handlers correctly allows both exceptions to be handled separately?

Try and except Medium
A. except BaseException before except TypeError
B. except ValueError before except Exception
C. except Exception before except ValueError
D. except ArithmeticError before except ZeroDivisionError

27 In a try statement, when is the else block executed?

Try and except Medium
A. When the try block raises no exception
B. When the finally block is skipped
C. When an exception remains unhandled
D. When any except block finishes

28 What is the main purpose of a finally block?

Try and except Medium
A. To suppress every raised exception
B. To retry the try block automatically
C. To run cleanup code regardless of errors
D. To handle only syntax errors

29 Which definition correctly creates a user-defined exception named InvalidAgeError?

User-defined exceptions Medium
A. class InvalidAgeError: raise Exception
B. def InvalidAgeError(Exception): pass
C. class InvalidAgeError(Exception): pass
D. exception InvalidAgeError(Exception): pass

30 Assume InsufficientFundsError is a valid exception class. Which statement raises it with a useful message?

User-defined exceptions Medium
A. raise InsufficientFundsError("Balance too low")
B. return InsufficientFundsError("Balance too low")
C. throw InsufficientFundsError("Balance too low")
D. except InsufficientFundsError("Balance too low")

31 Given class NegativeNumberError(Exception): pass, which handler catches that exception specifically?

User-defined exceptions Medium
A. except ValueError only:
B. except NegativeNumberError:
C. except raise NegativeNumberError:
D. catch NegativeNumberError:

32 A function must reject scores outside the range using InvalidScoreError. Which condition is correct?

User-defined exceptions Medium
A. if score < 0 and score > 100: raise InvalidScoreError()
B. if score < 0 or score > 100: raise InvalidScoreError()
C. if score == 0 or score == 100: raise InvalidScoreError()
D. if 0 < score < 100: raise InvalidScoreError()

33 Which file mode appends text to an existing file without removing its current contents?

Text file read/write operations Medium
A. "r"
B. "a"
C. "w"
D. "x"

34 What is an important benefit of using with open("notes.txt", "r") as file:?

Text file read/write operations Medium
A. The file becomes permanently read-only
B. The entire file is cached automatically
C. The file is closed automatically
D. All file errors are ignored automatically

35 Which method reads all remaining lines of a text file and returns them as a list of strings?

Text file read/write operations Medium
A. write()
B. readlines()
C. read()
D. readline()

36 After reading a file to its end, which operation moves the file cursor back to the beginning?

Text file read/write operations Medium
A. file.read(0)
B. file.seek(0)
C. file.reset(0)
D. file.tell(0)

37 What does file.write("Python") normally return when writing to a text file succeeds?

Text file read/write operations Medium
A. The value True
B. The value None
C. The number 6
D. The string "Python"

38 Which code correctly reads and parses JSON data from an already opened file object named file?

Reading JSON files Medium
A. data = json.load(file)
B. data = json.read(file)
C. data = file.json()
D. 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?

Reading JSON files Medium
A. "true" and "null"
B. 1 and 0
C. True and None
D. true and null

40 Which exception should be handled when a JSON file is opened successfully but contains malformed JSON syntax?

Reading JSON files Medium
A. json.JSONDecodeError
B. FileNotFoundError
C. PermissionError
D. UnicodeEncodeError

41 What happens when the following code is executed?

e = "outer"

try:

1 / 0

except ZeroDivisionError as e:

pass

print(e)

Built-in exceptions Hard
A. It prints outer.
B. It raises NameError.
C. It prints the caught exception.
D. It raises UnboundLocalError.

42 What value is returned by f()?

def f():

try:

return 1 / 0

except ZeroDivisionError:

return "except"

finally:

return "finally"

Try and except Hard
A. "except"
B. "finally"
C. No value; ZeroDivisionError escapes.
D. None

43 What is the outcome of this code?

try:

value = int("5")

except ValueError:

print("conversion failed")

else:

raise ValueError("later failure")

Try and except Hard
A. The except clause handles the later failure.
B. The else clause is skipped completely.
C. The program prints conversion failed.
D. The later ValueError propagates uncaught.

44 Which exception is not caught by the handler below under Python's standard exception hierarchy?

try:

operation()

except Exception:

recover()

Built-in exceptions Hard
A. RuntimeError
B. UnicodeError
C. KeyboardInterrupt
D. 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__)

Try and except Hard
A. ValueError
B. ZeroDivisionError
C. NoneType
D. 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")

User-defined exceptions Hard
A. It prints B.
B. It prints A.
C. It prints both A and B.
D. It raises CombinedError uncaught.

47 What exception actually results from executing raise CodeError?

class CodeError(Exception):

def __init__(self, code):

super().__init__(f"code={code}")

User-defined exceptions Hard
A. A CodeError containing the class name
B. A RuntimeError caused by invalid raising
C. A CodeError with an empty message
D. A 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")

User-defined exceptions Hard
A. ((), "AGE", "age")
B. (("AGE",), "age", "AGE")
C. (("age",), "age", "AGE")
D. (("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

User-defined exceptions Hard
A. result.__cause__ is the WrappedError itself.
B. result.__cause__ is the original ValueError.
C. result.__context__ is always set to None.
D. 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()

Text file read/write operations Hard
A. (3, "", 3)
B. (3, "abc", 3)
C. (3, "", 0)
D. (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)

Text file read/write operations Hard
A. data is "cde"; content is "XYcdef".
B. data is "abc"; content is "XYabcdef".
C. data is "cde"; content is "XYdef".
D. 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()

Text file read/write operations Hard
A. "abcX"
B. "Xabc"
C. "Xbc"
D. "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é𝄞")

Text file read/write operations Hard
A. 8, including an implicit terminator
B. 7, the number of UTF-8 bytes
C. 4, the number of Unicode units
D. 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"])

Text file read/write operations Hard
A. "abc\n"
B. "ab\nc"
C. "a\nb\nc\n"
D. "a b\n c"

55 According to Python's standard json module behavior, what value is produced by json.loads('{"x": 1, "x": 2}')?

Reading JSON files Hard
A. {"x": 1}
B. A JSONDecodeError
C. {"x": [1, 2]}
D. {"x": 2}

56 What is assigned to result?

result = json.loads(

'{"x": 1}',

object_hook=lambda obj: "OBJECT",

object_pairs_hook=lambda pairs: "PAIRS"

)

Reading JSON files Hard
A. {"x": 1}
B. "OBJECT"
C. "PAIRS"
D. A TypeError

57 What value is returned by the following call?

json.loads('[10, 2.5, 1e2]', parse_int=str)

Reading JSON files Hard
A. ["10", 2.5, "1e2"]
B. ["10", 2.5, 100.0]
C. ["10", "2.5", "1e2"]
D. [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}")

Reading JSON files Hard
A. It raises UnicodeDecodeError.
B. It raises JSONDecodeError.
C. It returns {"x": 1}.
D. It returns {"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)

Reading JSON files Hard
A. Both variables receive {"x": 1}.
B. The second call raises EOFError.
C. The second call raises JSONDecodeError.
D. second receives an empty dictionary.

60 What is the value of restored?

original = {1: "integer", "1": "string"}

restored = json.loads(json.dumps(original))

Reading JSON files Hard
A. {"1": "integer"}
B. {1: "integer", "1": "string"}
C. {"1": "string"}
D. A TypeError is raised.