0
0
Pythonprogramming~5 mins

Extending built-in exceptions in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AException
Bobject
Cint
Dlist
What does the super() function do in a custom exception's __init__ method?
ACreates a new exception
BCalls the parent class's __init__ method
CRaises the exception
DPrints the error message
How can you add extra information to a custom exception?
ABy using global variables
BBy changing the built-in Exception class
CBy raising multiple exceptions
DBy defining additional attributes in the class
What happens if you raise a custom exception but do not catch it?
AThe program continues silently
BThe exception is ignored
CThe program stops and shows a traceback
DThe exception is converted to a string
Which keyword is used to raise a custom exception?
Araise
Bthrow
Ccatch
Dtry
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.