Bird
Raised Fist0

Which code correctly implements this?

hard🚀 Application Q15 of Q15
Python - Exception Handling Fundamentals

You want to write a function that tries to convert a string to an integer and then divide 100 by that number. It should handle ValueError if conversion fails, ZeroDivisionError if division by zero happens, and print "Success" if no error occurs, and print "Done" regardless of errors. Which code correctly implements this?

Adef func(s): try: n = int(s) result = 100 / n except ValueError: print("Conversion error") except ZeroDivisionError: print("Division by zero") else: print("Success")
Bdef func(s): try: n = int(s) result = 100 / n except (ValueError, ZeroDivisionError): print("Error") finally: print("Success")
Cdef func(s): try: n = int(s) result = 100 / n except ValueError: print("Conversion error") except ZeroDivisionError: print("Division by zero") finally: print("Success")
Ddef func(s): try: n = int(s) result = 100 / n except ValueError: print("Conversion error") except ZeroDivisionError: print("Division by zero") else: print("Success") finally: print("Done")
Step-by-Step Solution
Solution:
  1. Step 1: Check handling of exceptions and success message

    Function must catch ValueError and ZeroDivisionError separately and print appropriate messages.
  2. Step 2: Check use of else and finally blocks

    else runs only if no exception, so "Success" should be printed there. finally always runs, so "Done" can be printed there.
  3. Step 3: Verify option correctness

    def func(s): try: n = int(s) result = 100 / n except ValueError: print("Conversion error") except ZeroDivisionError: print("Division by zero") else: print("Success") finally: print("Done") correctly uses separate except blocks, prints "Success" in else, and "Done" in finally.
  4. Final Answer:

    Option D code correctly implements all requirements -> Option D
  5. Quick Check:

    Separate except + else for success + finally for done [OK]
Quick Trick: Use else for success, finally for cleanup, separate except blocks [OK]
Common Mistakes:
MISTAKES
  • Printing success in finally instead of else
  • Combining exceptions in one except without separate messages
  • Omitting finally block when needed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes