The Exception Handler
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
- Asked in
- ING
Problem
Given a single list of [numerator, denominator] pairs, return a results list where for each pair you produce: the quotient numerator / denominator as a float on success; the string 'division by zero' when the denominator is 0; and the string 'invalid input' when either operand is not a number. Process every pair so that one bad pair never stops the rest, and return the results in the same order as the input.
Good code handles failure as gracefully as success.
Example
Input:
pairs = [[10,2],[5,0],["a",3]]
Output:
[5,"division by zero","invalid input"]
Worked solution and explanation
Why this problem exists in real interviews
This tests structured exception handling with multiple error types. It probes whether a candidate can distinguish error conditions, produce meaningful error messages, and process a batch of operations without letting one failure stop the rest.
Break down the requirements
Step 1: Iterate through each pair
Each pair is a [numerator, denominator] list. Unpack the two operands so you can validate and divide them.
Step 2: Validate, then divide with try/except
Before dividing, guard against non-numeric operands and return 'invalid input' for them, so a string operand does not get mistaken for a different error. Then attempt the division inside a try, catching ZeroDivisionError for a zero denominator.
Step 3: Return results or error messages
Append either the float quotient or the descriptive error string for each pair, preserving input order.
The solution
def safe_divide_batch(pairs: list) -> list:
results = []
for numerator, denominator in pairs:
if isinstance(numerator, bool) or isinstance(denominator, bool) \
or not isinstance(numerator, (int, float)) \
or not isinstance(denominator, (int, float)):
results.append('invalid input')
continue
try:
results.append(numerator / denominator)
except ZeroDivisionError:
results.append('division by zero')
return resultsCommon follow-up questions
- What if you also needed to handle integer overflow? (Tests awareness that Python has arbitrary-precision integers, so overflow does not occur natively.)
- How would you log the errors for debugging? (Tests structured logging with the exception traceback.)
- What if operations should stop on first error? (Tests early return vs batch processing design decisions.)