Challenge - 5 Problems
Exception Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of custom exception handling
What is the output of this code when the function is called?
Python
class MyError(Exception): pass def test(): try: raise MyError("Oops") except MyError as e: print(f"Caught: {e}") except Exception: print("General error") test()
Attempts:
2 left
💡 Hint
Look at which exception is raised and which except block catches it.
✗ Incorrect
The code raises MyError with message 'Oops'. The except block for MyError catches it and prints 'Caught: Oops'.
❓ Predict Output
intermediate2:00remaining
Output when subclass exception is raised
What will be printed when this code runs?
Python
class BaseError(Exception): pass class SubError(BaseError): pass try: raise SubError("Error happened") except BaseError as e: print(f"Handled: {e}")
Attempts:
2 left
💡 Hint
Remember subclass exceptions are caught by base class except blocks.
✗ Incorrect
SubError is a subclass of BaseError, so the except BaseError block catches it and prints the message.
❓ Predict Output
advanced2:00remaining
Output of exception with custom __str__ method
What is the output of this code?
Python
class CustomError(Exception): def __init__(self, code): self.code = code def __str__(self): return f"Error code: {self.code}" try: raise CustomError(404) except CustomError as e: print(e)
Attempts:
2 left
💡 Hint
The __str__ method controls the string shown when printing the exception.
✗ Incorrect
The __str__ method returns 'Error code: 404', so print(e) outputs that string.
❓ Predict Output
advanced2:00remaining
Exception chaining output
What will this code print?
Python
class FirstError(Exception): pass class SecondError(Exception): pass try: try: raise FirstError("First") except FirstError as e: raise SecondError("Second") from e except SecondError as e: print(f"Caught: {e}") print(f"Cause: {e.__cause__}")
Attempts:
2 left
💡 Hint
The 'from' keyword sets the __cause__ attribute to the original exception.
✗ Incorrect
The SecondError is raised from FirstError, so __cause__ holds the FirstError instance. Printing it shows 'First'.
🧠 Conceptual
expert3:00remaining
Correct way to create a custom exception with additional data
Which option correctly defines a custom exception class that stores an error code and message, and allows access to both after catching?
Attempts:
2 left
💡 Hint
Remember to call the base Exception __init__ with the message for proper behavior.
✗ Incorrect
Option A calls super().__init__(msg) to set the message properly and stores code separately. Others either don't call base __init__ correctly or store message in a non-standard attribute.