CCNA Exceptions and File I/O Questions

5 of 80 questions · Page 2/2 · Exceptions and File I/O · Answers revealed

76
MCQeasy

A small web application allows users to download files from a server. The code uses open() without any exception handling. When a user requests a non-existent file, the server crashes with a traceback and returns a 500 Internal Server Error to the client. The team needs to modify the code to handle this situation gracefully: if the file does not exist, the application should return a 404 Not Found response (by calling a function send_404()). The application should not catch unrelated exceptions like KeyboardInterrupt. Which modification is the most appropriate?

A.Wrap the entire request handling in a try-except block catching Exception, and if any exception occurs, call send_500().
B.Check if the file exists using os.path.exists before opening, and if not, call send_404().
C.Wrap the open() call in a try-except block catching OSError, and in the except block call send_404().
D.Wrap the open() call in a try-except block catching FileNotFoundError, and in the except block call send_404().
AnswerD

Specifically handles the missing file case without catching unrelated errors.

Why this answer

Option D is correct because it catches the specific exception raised when a file is not found (FileNotFoundError), which is a subclass of OSError. This allows the code to return a 404 response for missing files while not catching unrelated exceptions like KeyboardInterrupt, as required. The except block calls send_404() to handle the missing file gracefully without crashing the server.

Exam trap

Python Institute often tests the distinction between catching a specific exception (FileNotFoundError) versus its parent class (OSError), and the trap here is that candidates may choose the broader OSError (Option C) thinking it covers all file-related errors, but that would incorrectly handle permission or other OS errors as 404s.

How to eliminate wrong answers

Option A is wrong because it catches all exceptions (including KeyboardInterrupt) and calls send_500(), which does not distinguish between a missing file and other errors, violating the requirement to not catch unrelated exceptions. Option B is wrong because it introduces a race condition: between checking os.path.exists and opening the file, the file could be deleted or renamed, leading to an unhandled exception. Option C is wrong because catching OSError is too broad; it would catch other OS-related errors (e.g., permission denied) and incorrectly return a 404, when the requirement is to only handle non-existent files with a 404 response.

77
MCQmedium

A developer is implementing a custom exception for invalid data. Which class should the custom exception inherit from?

A.RuntimeError
B.ArithmeticError
C.BaseException
D.Exception
AnswerD

Standard base class for custom exceptions.

Why this answer

Option D is correct because the `Exception` class is the base class for all built-in, non-system-exiting exceptions in Python. Custom exceptions should inherit from `Exception` (or one of its subclasses) to ensure they are caught by generic `except Exception:` handlers and integrate properly with Python's exception hierarchy, while avoiding the system-exiting exceptions derived from `BaseException`.

Exam trap

The trap here is that candidates often choose `BaseException` thinking it is the most general base class, but Cisco tests the understanding that custom exceptions should inherit from `Exception` to avoid accidentally catching system-exiting exceptions like `KeyboardInterrupt`.

How to eliminate wrong answers

Option A is wrong because `RuntimeError` is a specific built-in exception for errors that do not fit into other categories; inheriting from it would misrepresent the custom exception's semantics and is not the recommended base for all custom exceptions. Option B is wrong because `ArithmeticError` is a narrow base for arithmetic-related errors (e.g., ZeroDivisionError); using it for generic invalid data exceptions would be semantically incorrect and overly restrictive. Option C is wrong because `BaseException` is the root of all exceptions, including system-exiting ones like `SystemExit` and `KeyboardInterrupt`; inheriting from it would cause the custom exception to be caught by `except BaseException:` blocks, which is not intended for user-defined exceptions and can suppress critical system signals.

78
MCQeasy

A developer writes a function that reads a configuration file and returns its contents as a string. The file might not exist. Which exception should be caught to handle a missing file?

A.FileNotFoundError
B.PermissionError
C.IOError
D.OSError
AnswerA

FileNotFoundError is specifically for missing files.

Why this answer

Option A is correct because `FileNotFoundError` is a built-in exception in Python that is raised when a file or directory is requested but does not exist. In Python 3, file-related I/O errors are organized under `OSError` with specific subclasses, and `FileNotFoundError` is the precise exception for a missing file, making it the most appropriate catch for this scenario.

Exam trap

Python Institute often tests the distinction between the broad `OSError` and its specific subclass `FileNotFoundError`, trapping candidates who think catching the parent class is safer, when in fact the exam expects precise exception handling for a missing file.

How to eliminate wrong answers

Option B is wrong because `PermissionError` is raised when the file exists but the process lacks the required permissions to access it, not when the file is missing. Option C is wrong because `IOError` was an alias for `OSError` in Python 2 but is no longer a separate exception in Python 3; catching it would not specifically target a missing file and is considered deprecated. Option D is wrong because `OSError` is the parent class for all system-related exceptions, including `FileNotFoundError`, but catching the parent is too broad and does not precisely handle the missing file case; it would also catch unrelated OS errors like permission or disk errors.

79
Multi-Selecteasy

Which TWO of the following are correct ways to raise a custom exception in Python? (Assume CustomError and CustomException are user-defined.)

Select 2 answers
A.raise "Custom error"
B.raise 42
C.raise CustomError("invalid")
D.raise Exception
E.raise CustomException()
AnswersC, E

Valid: raises a custom exception instance.

Why this answer

Option C is correct because it raises a user-defined exception by instantiating the custom exception class `CustomError` with an argument (the string "invalid"). In Python, the `raise` statement must be followed by an exception instance or an exception class; `CustomError("invalid")` creates an instance of the custom exception, which is the proper way to raise a custom exception with a custom message.

Exam trap

Python Institute often tests the distinction between raising an exception class versus an exception instance, and the fact that only instances (or classes that are subclasses of `BaseException`) are valid arguments to `raise` — candidates mistakenly think any object can be raised or that raising a class without instantiation is the only correct way.

80
MCQmedium

A data scientist writes a script to parse a configuration file that contains lines in 'key=value' format. Some lines may have malformed data that cause a ValueError when trying to convert the value to an integer. The requirement is to process all valid lines and skip any that cause a ValueError, but continue processing subsequent lines. The script should log a warning for each skipped line, including the line number. Which implementation correctly fulfills this requirement? (Assume the file is opened with 'with open(...) as f'.)

A.Inside a for loop over f, wrap the parsing in a try-except ValueError block, log the error, and continue.
B.Wrap the entire file processing in a try-except ValueError block; if an error occurs, log and break.
C.Before parsing, check if the value string consists of digits using str.isdigit; if not, skip the line.
D.Inside a for loop over f, wrap the parsing in a try-except Exception block, log the error, and continue.
AnswerA

Specifically catches the expected error and continues processing.

Why this answer

Option A is correct because it uses a try-except ValueError block inside the for loop, which catches the specific exception when converting the value to an integer, logs a warning with the line number, and continues to the next line. This ensures all valid lines are processed while malformed lines are skipped without halting execution, fulfilling the requirement exactly.

Exam trap

Python Institute often tests the distinction between catching specific exceptions (ValueError) versus broad exceptions (Exception), and the trap here is that candidates may choose Option D thinking 'Exception' covers all errors, but it violates the principle of catching only what you can handle and may hide bugs.

How to eliminate wrong answers

Option B is wrong because wrapping the entire file processing in a try-except ValueError block will cause the loop to break on the first error, skipping all subsequent lines, which violates the requirement to continue processing. Option C is wrong because using str.isdigit() is unreliable for integer conversion—it returns False for negative numbers (e.g., '-5') or strings with leading zeros (e.g., '007'), causing valid lines to be incorrectly skipped. Option D is wrong because catching a broad 'Exception' instead of the specific 'ValueError' can mask unrelated errors (e.g., KeyError, TypeError) that should not be silently skipped, violating best practices for exception handling.

← PreviousPage 2 of 2 · 80 questions total

Ready to test yourself?

Try a timed practice session using only Exceptions and File I/O questions.