Complete the code to catch a division by zero error.
try: result = 10 / 0 except [1]: print("Cannot divide by zero")
The ZeroDivisionError is raised when dividing by zero. Catching this exception allows the program to handle it gracefully.
Complete the code to print a message when no error occurs.
try: print("Hello") except Exception: print("Error occurred") else: [1]
raise inside else which re-raises an error.break outside loops causing syntax error.The else block runs only if no exception occurs. Printing a message here confirms no errors happened.
Fix the error in the except block to catch any exception.
try: x = int('abc') except [1]: print("Caught an error")
Error which is not a built-in exception class.BaseException which is too broad and not recommended.Exception is the base class for most errors and is commonly used to catch any error except system-exiting ones.
Fill both blanks to handle a file error and print a message.
try: with open('file.txt', '[1]') as f: content = f.read() except [2]: print("File not found")
Opening a file for reading uses mode 'r'. If the file does not exist, Python raises FileNotFoundError.
Fill all three blanks to handle multiple exceptions and print the error type.
try: num = int(input('Enter a number: ')) result = 10 / num except [1]: print("Cannot convert input to integer") except [2]: print("Division by zero error") except [3]: print("Some other error occurred")
ValueError handles invalid integer conversion, ZeroDivisionError handles division by zero, and Exception catches any other errors.