0
0
Pythonprogramming~20 mins

Why custom exceptions are needed in Python - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Custom Exceptions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why create custom exceptions?

Why do programmers create custom exceptions instead of using only built-in exceptions?

ATo provide more specific error messages that match the program's unique needs.
BBecause built-in exceptions cannot be caught by try-except blocks.
CTo make the program run faster by avoiding built-in exceptions.
DTo automatically fix errors without user intervention.
Attempts:
2 left
💡 Hint

Think about how specific error messages help understand problems better.

Predict Output
intermediate
2:00remaining
Output of custom exception handling

What will be the output of this code?

Python
class MyError(Exception):
    pass

try:
    raise MyError('Oops!')
except MyError as e:
    print(f'Caught custom error: {e}')
except Exception:
    print('Caught general error')
ASyntaxError
BCaught general error
CNo output
DCaught custom error: Oops!
Attempts:
2 left
💡 Hint

Look at which exception is raised and which except block catches it.

Predict Output
advanced
2:00remaining
Handling multiple custom exceptions

What will be printed when this code runs?

Python
class ErrorA(Exception):
    pass

class ErrorB(Exception):
    pass

def test_error(e):
    try:
        raise e
    except ErrorA:
        print('Caught ErrorA')
    except ErrorB:
        print('Caught ErrorB')
    except Exception:
        print('Caught general exception')

test_error(ErrorB('error'))
ACaught general exception
BCaught ErrorB
CCaught ErrorA
DNo output
Attempts:
2 left
💡 Hint

Check which exception is raised and which except block matches it first.

🧠 Conceptual
advanced
2:00remaining
Why not use only built-in exceptions?

Which of these is NOT a good reason to create custom exceptions?

ATo confuse other programmers by adding unnecessary complexity.
BTo make error handling more precise and meaningful.
CTo clearly separate different error types in your program.
DTo provide better messages for specific error cases.
Attempts:
2 left
💡 Hint

Think about the purpose of custom exceptions in teamwork and code clarity.

Predict Output
expert
2:00remaining
Output with inheritance in custom exceptions

What is the output of this code?

Python
class BaseError(Exception):
    pass

class ChildError(BaseError):
    pass

try:
    raise ChildError('child error occurred')
except BaseError as e:
    print(f'Caught base error: {e}')
except ChildError:
    print('Caught child error')
ACaught child error
BNo output
CCaught base error: child error occurred
DTypeError
Attempts:
2 left
💡 Hint

Remember that except blocks are checked in order and inheritance matters.