0
0
Pythonprogramming~20 mins

Exception hierarchy in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Exception Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of exception handling with hierarchy
What is the output of this code snippet?
Python
class MyError(Exception):
    pass

class MySubError(MyError):
    pass

try:
    raise MySubError("Oops")
except MyError:
    print("Caught MyError")
except Exception:
    print("Caught Exception")
ANo output
BCaught Exception
CRuntimeError
DCaught MyError
Attempts:
2 left
💡 Hint
Remember that catching a base exception also catches its subclasses.
Predict Output
intermediate
2:00remaining
Exception hierarchy and multiple except blocks
What will be printed when this code runs?
Python
try:
    raise KeyError('key')
except LookupError:
    print('Caught LookupError')
except KeyError:
    print('Caught KeyError')
ACaught LookupError
BCaught KeyError
CNo output
DKeyError not caught
Attempts:
2 left
💡 Hint
Check the order of except blocks and exception inheritance.
Predict Output
advanced
2:30remaining
Output of exception chaining with hierarchy
What is the output of this code?
Python
class BaseError(Exception):
    pass

class DerivedError(BaseError):
    pass

try:
    try:
        raise DerivedError('inner')
    except DerivedError as e:
        raise BaseError('outer') from e
except BaseError as e:
    print(type(e).__name__)
    print(type(e.__cause__).__name__)
ADerivedError\nDerivedError
BBaseError\nBaseError
CBaseError\nDerivedError
DDerivedError\nBaseError
Attempts:
2 left
💡 Hint
Look at the exception chaining with 'from' keyword.
Predict Output
advanced
2:00remaining
Exception hierarchy and catching order
What will this code print?
Python
class A(Exception):
    pass

class B(A):
    pass

class C(B):
    pass

try:
    raise C()
except B:
    print('Caught B')
except A:
    print('Caught A')
ACaught B
BCaught A
CNo output
DRuntimeError
Attempts:
2 left
💡 Hint
The first matching except block is executed.
🧠 Conceptual
expert
1:30remaining
Identify the base class of all built-in exceptions
Which class is the base class for all built-in exceptions in Python?
AException
BBaseException
CStandardError
DError
Attempts:
2 left
💡 Hint
This class is the root of the exception hierarchy and includes system-exiting exceptions.