Complete the code to catch a ZeroDivisionError exception.
try: result = 10 / 0 except [1]: print("Cannot divide by zero")
The ZeroDivisionError exception is raised when dividing by zero. Catching it allows the program to handle this error gracefully.
Complete the code to print 'Success' only if no exception occurs.
try: x = 5 / 1 except ZeroDivisionError: print("Error") else: print([1])
The else block runs only if the try block has no exceptions. So it prints "Success" here.
Fix the error in the code to correctly handle exceptions and print 'No error' if none occur.
try: value = int('abc') except ValueError: print("Conversion failed") else: print([1])
The print statement needs a string in quotes. Without quotes, it causes a NameError.
Fill both blanks to create a try-except-else that prints the square root if no error occurs and prints 'Error' if a ValueError happens.
import math try: num = int(input('Enter a number: ')) result = math.sqrt(num) except [1]: print('Error') else: print([2])
The except block should catch ValueError from invalid int conversion. The else block prints the computed result.
Fill all three blanks to create a try-except-else that divides two numbers, catches ZeroDivisionError, and prints the quotient if no error.
try: numerator = 10 denominator = 2 quotient = numerator [1] denominator except [2]: print('Cannot divide by zero') else: print([3])
The division operator is /. The exception to catch is ZeroDivisionError. The else block prints the quotient.