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. ValueError
B. IndexError
C. ZeroDivisionError
D. TypeError

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

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

3 Which exception occurs when an undefined variable is used?

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

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

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

5 What is the main purpose of a try block?

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

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

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

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

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

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

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

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

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

10 Which keyword is used to trigger an exception intentionally?

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

11 Which statement correctly defines a custom exception named AgeError?

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

12 How can a custom exception named AgeError be triggered?

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

13 Which file mode opens a text file for reading?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

21 What exception is raised by the following code?

result = 15 / int("0")

Built-in exceptions Medium
A. ArithmeticError
B. TypeError
C. ValueError
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. KeyError
C. NameError
D. IndexError

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

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

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

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

25 What is printed by the following code?

try:

value = int("abc")

except ValueError:

print("Invalid")

else:

print("Valid")

Try and except Medium
A. Invalid
B. Nothing is printed
C. Valid
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 ValueError before except Exception
B. except Exception before except ValueError
C. except ArithmeticError before except ZeroDivisionError
D. except BaseException before except TypeError

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 handle only syntax errors
B. To suppress every raised exception
C. To retry the try block automatically
D. To run cleanup code regardless of errors

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

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

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

User-defined exceptions Medium
A. except InsufficientFundsError("Balance too low")
B. throw InsufficientFundsError("Balance too low")
C. return InsufficientFundsError("Balance too low")
D. raise 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. catch NegativeNumberError:
D. except raise NegativeNumberError:

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

User-defined exceptions Medium
A. if score < 0 or score > 100: raise InvalidScoreError()
B. if 0 < score < 100: raise InvalidScoreError()
C. if score == 0 or score == 100: raise InvalidScoreError()
D. if score < 0 and 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. "x"
B. "w"
C. "a"
D. "r"

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

Text file read/write operations Medium
A. The entire file is cached automatically
B. The file is closed automatically
C. The file becomes permanently read-only
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. readline()
C. readlines()
D. read()

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.seek(0)
B. file.read(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 number 6
B. The value True
C. The value None
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.loads(file)
C. data = json.read(file)
D. data = file.json()

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. "true" and "null"
C. True and None
D. 1 and 0

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 raises UnboundLocalError.
B. It prints the caught exception.
C. It raises NameError.
D. It prints outer.

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. No value; ZeroDivisionError escapes.
B. "finally"
C. "except"
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 else clause is skipped completely.
B. The except clause handles the later failure.
C. The later ValueError propagates uncaught.
D. The program prints conversion failed.

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. ArithmeticError
D. 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__)

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

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

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 TypeError caused by missing code
B. A CodeError containing the class name
C. A RuntimeError caused by invalid raising
D. A 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")

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

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

Text file read/write operations Hard
A. "Xbc"
B. "Xabc"
C. "abcX"
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. 4, the number of Unicode units
C. 3, the number of characters
D. 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"])

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

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, 2]}
B. {"x": 2}
C. A JSONDecodeError
D. {"x": 1}

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. "PAIRS"
B. {"x": 1}
C. A TypeError
D. "OBJECT"

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, 100.0]
D. ["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}")

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

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

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", "1": "string"}
B. {"1": "string"}
C. A TypeError is raised.
D. {"1": "integer"}