Bird
Raised Fist0
Pythonprogramming~10 mins

Extending built-in exceptions in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Extending built-in exceptions
Define new Exception class
Inherit from built-in Exception
Add custom __init__ or methods
Raise new Exception
Catch with try-except
Handle or print custom message
You create a new error type by making a class that inherits from a built-in exception, then raise and catch it like normal.
Execution Sample
Python
class MyError(Exception):
    def __init__(self, message):
        super().__init__(message)

try:
    raise MyError("Oops!")
except MyError as e:
    print(e)
This code defines a new error type MyError, raises it with a message, and catches it to print the message.
Execution Table
StepActionEvaluationResult
1Define class MyError inheriting ExceptionClass createdMyError ready to use
2Enter try blockNo error yetProceed
3Raise MyError with message 'Oops!'Exception raisedJump to except block
4Catch MyError as ee holds MyError instanceReady to handle
5Print(e)Calls __str__ on MyError instanceOutput: Oops!
💡 Exception handled, program continues normally after except block
Variable Tracker
VariableStartAfter Step 3After Step 4Final
eundefinedMyError('Oops!')MyError('Oops!')MyError('Oops!')
Key Moments - 3 Insights
Why do we inherit from Exception when creating MyError?
Inheriting from Exception makes MyError behave like a normal error, so it can be raised and caught properly (see Step 1 and Step 3 in execution_table).
What happens when we raise MyError inside try?
Raising MyError stops normal flow and jumps to the except block that matches MyError (Step 3 and Step 4).
How does print(e) show 'Oops!'?
The message is stored in the Exception base class and __str__ returns it, so print(e) outputs the message passed when raising (Step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'e' after Step 3?
AMyError('Oops!')
Bundefined
CException('Oops!')
DNone
💡 Hint
Check variable_tracker row for 'e' after Step 3
At which step does the program jump to the except block?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
See execution_table Action and Result columns at Step 3
If we did not inherit from Exception, what would happen when raising MyError?
AIt would raise normally and be caught
BIt would cause a TypeError
CIt would not be recognized as an exception
DIt would print 'Oops!' anyway
💡 Hint
Refer to key_moments about why inheritance from Exception is needed
Concept Snapshot
class MyError(Exception):
    def __init__(self, message):
        super().__init__(message)

Raise with: raise MyError('msg')
Catch with: except MyError as e:
Use inheritance to behave like built-in exceptions.
Full Transcript
This example shows how to create a new error type by making a class that inherits from Exception. When we raise this new error inside a try block, the program jumps to the matching except block. The error message is stored and printed when we print the caught exception. This helps us make custom errors with special messages or behavior while keeping normal error handling.

Practice

(1/5)
1. What is the main reason to extend built-in exceptions in Python?
easy
A. To create custom error types that describe specific problems clearly
B. To make the program run faster
C. To avoid using try-except blocks
D. To automatically fix errors when they occur

Solution

  1. Step 1: Understand the purpose of exceptions

    Exceptions help signal errors or unusual situations in a program.
  2. Step 2: Why extend built-in exceptions?

    Extending allows creating specific error types that explain problems clearly and help debugging.
  3. Final Answer:

    To create custom error types that describe specific problems clearly -> Option A
  4. Quick Check:

    Custom exceptions = clearer error messages [OK]
Hint: Custom exceptions clarify errors, not speed or auto-fix [OK]
Common Mistakes:
  • Thinking extending exceptions speeds up code
  • Believing exceptions fix errors automatically
  • Confusing exceptions with avoiding try-except
2. Which of the following is the correct way to define a custom exception named MyError that extends ValueError?
easy
A. def MyError(ValueError): pass
B. class MyError(ValueError): pass
C. class MyError: ValueError
D. exception MyError(ValueError): pass

Solution

  1. Step 1: Recognize class syntax for exceptions

    Custom exceptions are classes that inherit from built-in exceptions.
  2. Step 2: Check correct Python class definition

    Use class MyError(ValueError): pass to extend ValueError properly.
  3. Final Answer:

    class MyError(ValueError): pass -> Option B
  4. Quick Check:

    Use class + inheritance syntax for exceptions [OK]
Hint: Use class keyword and inherit from built-in exception [OK]
Common Mistakes:
  • Using def instead of class
  • Wrong inheritance syntax
  • Using 'exception' keyword which doesn't exist
3. What will be the output of this code?
class MyError(Exception):
    pass

try:
    raise MyError('Oops!')
except MyError as e:
    print(e)
medium
A. MyError
B. Exception
C. Oops!
D. No output

Solution

  1. Step 1: Understand raising and catching custom exception

    The code raises MyError with message 'Oops!'.
  2. Step 2: What does print(e) show?

    Printing the exception variable e shows the message passed during raise.
  3. Final Answer:

    Oops! -> Option C
  4. Quick Check:

    Exception message prints when caught and printed [OK]
Hint: Print exception object to see its message [OK]
Common Mistakes:
  • Printing exception class name instead of message
  • Expecting no output because of exception
  • Confusing exception type with message
4. Identify the error in this custom exception definition:
class CustomError(Exception):
    def __init__(self, message):
        print(message)
medium
A. Exception cannot be extended
B. Class name should be lowercase
C. print() cannot be used in __init__
D. Missing call to super().__init__(message) in __init__

Solution

  1. Step 1: Check __init__ method in custom exception

    Custom exceptions should call the parent Exception __init__ to set the message properly.
  2. Step 2: Why call super().__init__(message)?

    This ensures the message is stored and accessible like normal exceptions.
  3. Final Answer:

    Missing call to super().__init__(message) in __init__ -> Option D
  4. Quick Check:

    Always call super().__init__ in custom exception init [OK]
Hint: Call super().__init__ to set message in custom exceptions [OK]
Common Mistakes:
  • Forgetting super().__init__ call
  • Thinking print replaces message storage
  • Believing class names must be lowercase
5. You want to create a custom exception ValidationError that stores an error code along with the message. Which code correctly implements this?
hard
A. class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code
B. class ValidationError(Exception): def __init__(self, message, code): self.message = message self.code = code
C. class ValidationError(Exception): def __init__(self, code): super().__init__(code) self.message = ''
D. class ValidationError(Exception): def __init__(self, message): super().__init__(message) self.code = None

Solution

  1. Step 1: Understand storing extra info in custom exceptions

    We want to keep both message and code, so __init__ must accept both.
  2. Step 2: Properly call super().__init__ with message and store code

    class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code calls super().__init__(message) to set message and saves code as attribute.
  3. Final Answer:

    class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code -> Option A
  4. Quick Check:

    Call super with message, store extra attributes separately [OK]
Hint: Call super with message, save extra data as attributes [OK]
Common Mistakes:
  • Not calling super().__init__ with message
  • Not storing extra info as attributes
  • Mixing message and code parameters