Python Assignment– 6

Exception Handling

Basic Questions

  1. Intentionally write code that triggers a ‘SyntaxError’ (e.g., missing closing parenthesis), then fix it and run successfully; print a line describing the difference between ‘syntax’, ‘runtime’, and ‘logical’ errors.
  2. Trigger a ‘ZeroDivisionError’ by computing ’10 / 0′ inside a ‘try’ block and catch it with ‘except ZeroDivisionError’ to print ‘cannot divide by zero’.
  3. Read input for an integer using ‘int(input())’ inside ‘try’ and catch ‘ValueError’ to print ‘invalid integer’; otherwise print the parsed integer.
  4. Access a missing key from a dictionary inside ‘try’ and catch ‘KeyError’ to print ‘missing key’; then access an existing key and print its value.
  5. Open a non-existent file using ‘open’ inside ‘try’ and catch ‘FileNotFoundError’ to print a friendly message.
  6. Convert a string to float inside ‘try’ and catch ‘ValueError’; on success, print the square of the float.
  7. Use ‘list.index’ to search for an element that is not present; catch ‘ValueError’ and print ‘not found’.
  8. Use ‘try-except’ to call ‘int(” 42 “)’ and confirm it succeeds; print the result in ‘else’ when no exception occurs.
  9. In a ‘try’ block, divide two numbers; catch both ‘ZeroDivisionError’ and ‘TypeError’ using two separate ‘except’ clauses and print which exception occurred.
  10. Wrap an operation in ‘try-except-finally’ that prints ‘cleanup’ in ‘finally’ regardless of outcome; deliberately cause one run to fail and one to succeed.
  11. Use a single ‘except (ValueError, TypeError)’ tuple to handle bad input when converting a mixed list to integers; print the count of failures.
  12. Write a small function ‘parse_age’ that returns an ‘int’ from a string using ‘try-except’ and returns ‘-1’ on ‘ValueError’; demonstrate with valid and invalid inputs.
  13. Access ‘my_list[100]’ inside ‘try’ and catch ‘IndexError’; print the list length in the ‘except’ block.
  14. Use ‘dict.get’ as a safe alternative to avoid ‘KeyError’; print the default value when key is missing and compare with ‘try-except’ approach.
  15. Deliberately raise a ‘ValueError’ using ‘raise ValueError(“negative not allowed”)’ when a read number is negative; catch and print the error message.
  16. Create and raise a generic ‘Exception’ with a custom message; catch it and print ‘handled generic exception’.
  17. Demonstrate a ‘finally’ that closes a file handle: open a file for writing in ‘try’, write one line, and close it in ‘finally’ even if an exception occurs in between.
  18. Show a logical error by computing average with wrong denominator; correct it and print both results for comparison.
  19. Use ‘assert’ to validate that an input number is positive; catch the resulting ‘AssertionError’ with ‘try-except’ and print ‘assert failed’.
  20. Add a minimal input validation that rejects empty strings by raising ‘ValueError’ and catches it to print ’empty not allowed’.

Intermediate Questions

  1. Build ‘safe_div(a, b)’ that returns ‘a / b’ using ‘try-except-else-finally’; in ‘else’ print ‘ok’, in ‘finally’ print ‘done’, and on ‘ZeroDivisionError’ return ‘None’.
  2. Read a line of comma-separated integers; parse them with ‘int’ in a loop wrapped in ‘try-except’; skip invalid tokens and print a list of successfully parsed integers.
  3. Implement ‘read_config(d, key, default=None)’ that tries ‘d[key]’ inside ‘try’ and falls back to ‘default’ on ‘KeyError’; print the retrieved value.
  4. Write ‘open_then_parse_float(path)’ that opens a file, reads one line, converts to ‘float’ with ‘try-except’ catching ‘FileNotFoundError’ and ‘ValueError’ separately; print clear messages for each.
  5. Create ‘first_int(tokens)’ that returns the first token convertible to ‘int’ using a loop with ‘try-except’; if none convert, raise ‘ValueError(“no int found”)’ and catch it where called.
  6. Use ‘multiple except’ ordering to handle ‘OSError’ before its subclass ‘FileNotFoundError’ and demonstrate why order matters by showing different outputs when reversed.
  7. Build ‘safe_getitem(seq, i)’ that tries to access ‘seq[i]’ and catches ‘IndexError’ and ‘TypeError’; return ‘None’ on error and print which error occurred.
  8. Implement ‘ensure_positive(n)’ that raises ‘TypeError’ if ‘n’ is not an ‘int’ and ‘ValueError’ if ‘n <= 0’; wrap calls in ‘try-except’ to display distinct messages.
  9. Demonstrate exception chaining by catching a ‘ValueError’ from ‘int(x)’, then raising a new ‘RuntimeError’ with ‘raise … from e’ and printing the ’cause’ message.
  10. Write ‘load_json_like(text)’ that attempts ‘eval(text)’ inside ‘try’ only after validating that the text contains only digits, braces, brackets, colons, commas, quotes, spaces (simple whitelist); on validation failure, raise ‘ValueError(“unsafe input”)’; catch and report safely.
  11. Create ‘call_with_retries(fn, times=3)’ that catches any ‘Exception’, prints the attempt number, and retries up to ‘times’; after exhausting attempts, re-raise the last exception.
  12. Build a mini parser for ‘key=value’ pairs; for each malformed pair, catch an error and collect it in a list ‘errors’; at the end, print ‘errors’ and the successfully parsed dict.
  13. Write ‘divide_all(nums, d)’ that divides each element by ‘d’; catch ‘ZeroDivisionError’ and return the original list unchanged; otherwise return the divided list.
  14. Demonstrate ‘try-except-else’ by attempting to pop from a non-empty list (should go to ‘else’) and from an empty list (should go to ‘except IndexError’).
  15. Create a function that wraps another function and converts any ‘KeyError’ to a ‘ValueError’ while preserving the original message; show both before and after behavior.
  16. Implement ‘safe_int_map(strings)’ using a list comprehension that internally uses a helper with ‘try-except’ (no bare ‘except’); non-convertible items should map to ‘None’.
  17. Read from an environment-like dict; if a required key is missing, raise a custom ‘ConfigError’ (defined by you) with a helpful message and catch it at the call site.
  18. Write a file-copy simulation that raises ‘PermissionError’ for a protected path and ‘FileNotFoundError’ for a missing source; handle both specifically and print user-friendly text.
  19. Use ‘finally’ to release a fake lock object regardless of success or failure; simulate success and failure paths and print lock state transitions.
  20. Show best practice of logging inside ‘except’ by printing ‘repr(e)’ and not exposing sensitive data (like passwords) when a ‘ValueError’ occurs during parsing of a credentials string.

Advanced Questions

  1. Define a custom exception hierarchy: ‘AppError(Exception)’ as base, with ‘ConfigError(AppError)’, ‘ValidationError(AppError)’, and ‘RetryableError(AppError)’; write a function that raises each based on input and handle them with ordered ‘except’ clauses.
  2. Create ‘sanitize_and_parse_int(text)’ that first validates input with a whitelist (digits and optional leading sign), then converts to ‘int’ inside ‘try’; raise ‘ValidationError’ on bad input; demonstrate secure handling without ‘eval’ or unsafe parsing.
  3. Implement a transaction-like function ‘transfer(balance, amount)’ that raises ‘ValueError’ for negative amounts and ‘RuntimeError’ for insufficient funds; ensure ‘finally’ logs ‘audit complete’ whether the transfer succeeded or failed.
  4. Build ‘with_resources()’ that acquires two resources and ensures both are released using nested ‘try-finally’ blocks; deliberately raise an error after acquiring the first resource to demonstrate correct cleanup order.
  5. Write ‘parse_csv_line(line)’ that splits a CSV-like string; raise ‘ValueError’ if the field count is unexpected; catch the error and continue processing the remaining lines while collecting failures.
  6. Implement ‘retry_on(exception_types, times)’ that returns a decorator; the decorator retries the wrapped function when exceptions in ‘exception_types’ occur; test with a function that fails twice with ‘RetryableError’ and then succeeds.
  7. Create ‘strict_dict’ class that overrides ‘getitem’ to raise ‘KeyError’ with a detailed message listing available keys; show usage in ‘try-except-else’ and print the message.
  8. Build ‘safe_execute(func, *args, **kwargs)’ that executes ‘func’ and returns a tuple ‘(ok, result_or_error)’; never let exceptions escape, and ensure ‘finally’ prints ‘finished’; demonstrate with a function that sometimes raises.
  9. Implement a robust input pipeline that reads tokens, validates type and bounds, and uses specific exceptions (‘ValueError’, ‘OverflowError’) and a custom ‘RangeError’; handle each with distinct messages and continue processing the rest of the tokens.
  10. Write a short checklist printer for best practices in secure exception handling that outputs lines such as ‘avoid bare except’, ‘validate inputs before use’, ‘do not leak secrets in error messages’, ‘log with context but sanitize data’, and ‘use specific exceptions not generic ones’; ensure each line is printed from a list to simulate enforceable guidelines.