Consider the following Python code that raises an exception. What will be printed when this code runs?
def check_age(age): if age < 18: raise ValueError("Age must be at least 18") return "Access granted" try: print(check_age(16)) except ValueError as e: print(f"Error: {e}")
Think about what happens when raise is called inside the function and how the try-except block handles it.
The function check_age raises a ValueError when the age is less than 18. The try-except block catches this exception and prints the error message prefixed by "Error:".
Look at this code snippet. What error will it raise when executed?
def divide(x, y): if y == 0: raise ZeroDivisionError("Cannot divide by zero") return x / y result = divide(10, 0)
Check the condition that triggers the raise statement and the type of exception raised.
The function explicitly raises a ZeroDivisionError with the message "Cannot divide by zero" when the divisor is zero.
Analyze this code that raises exceptions inside nested try-except blocks. What will be printed?
def func(): try: raise KeyError("Key missing") except KeyError: raise ValueError("Value error raised") try: func() except ValueError as e: print(f"Caught: {e}")
Notice the exception raised inside the except block and which exception is caught outside.
The func raises a KeyError, which is caught and replaced by raising a ValueError. The outer try-except catches the ValueError and prints its message.
What will be the output of this code that raises an exception without a message?
try: raise RuntimeError except RuntimeError as e: print(f"Caught an error: {e}")
Check what the exception object e contains when no message is provided.
When an exception is raised without a message, its string representation is empty, so printing {e} shows an empty string after the colon.
You want to create and raise a custom exception MyError with the message "Something went wrong". Which option does this correctly?
Remember how to define a custom exception and pass a message when raising it.
Option C defines a custom exception class and raises it with a message directly. Option C requires calling MyError() without arguments but sets the message in __init__. Option C raises the class, not an instance, causing a TypeError. Option C does not call super().__init__, so the message is not set properly.