Hackerrank File I/O and Exception Handling 2 — Questions and Answers
Question 1: Which Python keyword starts a block that catches exceptions?
- catch
- rescue
- except (Correct answer)
- handle
Correct answer: except
Python uses `except` (paired with `try`) to catch and handle exceptions, unlike Java/C++ which use `catch`.
Question 2: Which clause in a try/except construct always executes regardless of whether an exception occurred?
- else
- finally (Correct answer)
- default
- always
Correct answer: finally
The `finally` clause executes unconditionally after the try and any except blocks, making it ideal for cleanup code.
Question 3: How do you re-raise the currently-handled exception inside an except block without losing the traceback?
- raise Exception()
- raise (Correct answer)
- throw
- reraise()
Correct answer: raise
A bare `raise` statement inside an except block re-raises the current exception preserving the original traceback.
Question 4: What is the base class for all built-in, non-system-exiting exceptions in Python?
- BaseException
- Exception (Correct answer)
- RuntimeError
- StandardError
Correct answer: Exception
`Exception` is the base class for all built-in exceptions that programs are expected to catch; `BaseException` also includes SystemExit and KeyboardInterrupt.
Question 5: Which except clause syntax lets you capture the exception instance as a variable named 'e'?
- except Exception: e
- except(Exception) as e:
- except Exception as e: (Correct answer)
- except e = Exception:
Correct answer: except Exception as e:
The `except ExceptionType as variable:` syntax binds the caught exception instance to the given variable name.
Question 6: Which block runs only if no exception was raised in the try block?
- finally
- always
- else (Correct answer)
- success
Correct answer: else
The `else` clause after an except block executes only when the try block completed without raising any exception.
Question 7: What exception is raised when code tries to divide an integer by zero?
- ValueError
- ArithmeticError
- ZeroDivisionError (Correct answer)
- MathError
Correct answer: ZeroDivisionError
`ZeroDivisionError` is raised for division or modulo operations where the divisor is zero.
Which Python keyword starts a block that catches exceptions?