Recall & Review
beginner
What is the purpose of extending built-in exceptions in Python?
Extending built-in exceptions allows you to create custom error types that behave like standard errors but can carry specific information or handle special cases in your program.
Click to reveal answer
beginner
How do you define a custom exception by extending a built-in exception?
You create a new class that inherits from a built-in exception class like Exception or ValueError, for example: <pre>class MyError(Exception):
pass</pre>Click to reveal answer
intermediate
Why might you want to add an __init__ method to your custom exception?
Adding an __init__ method lets you store extra information about the error, like a message or error code, which can be accessed when handling the exception.
Click to reveal answer
intermediate
What does the following code do?<br><pre>class MyError(Exception):
def __init__(self, message, code):
super().__init__(message)
self.code = code</pre>It defines a custom exception MyError that takes a message and a code. The message is passed to the base Exception class, and the code is stored as an attribute for extra error info.
Click to reveal answer
beginner
How do you raise and catch a custom exception?
You use the raise keyword to throw the exception and a try-except block to catch it:<br>
try:
raise MyError('Oops', 404)
except MyError as e:
print(f'Error: {e}, code: {e.code}')Click to reveal answer
Which built-in class should you usually inherit from to create a custom exception?
✗ Incorrect
Custom exceptions should inherit from Exception or one of its subclasses to behave like standard errors.
What does the super() function do in a custom exception's __init__ method?
✗ Incorrect
super() calls the parent class's __init__ to properly initialize the base Exception part.
How can you add extra information to a custom exception?
✗ Incorrect
You add extra attributes in your custom exception class to store additional error details.
What happens if you raise a custom exception but do not catch it?
✗ Incorrect
Uncaught exceptions stop the program and print an error traceback.
Which keyword is used to raise a custom exception?
✗ Incorrect
The raise keyword is used to throw exceptions in Python.
Explain how to create and use a custom exception in Python.
Think about making a new class and how to handle errors.
You got /4 concepts.
Why is it useful to extend built-in exceptions instead of using Exception directly?
Consider how different errors help you understand problems better.
You got /4 concepts.