Bird
Raised Fist0
Pythonprogramming~10 mins

Creating exception classes in Python - Visual Walkthrough

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 - Creating exception classes
Define new Exception class
Raise the new Exception
Catch the Exception with try-except
Handle or print error message
End
You first create a new exception class, then raise it in code, catch it using try-except, and finally handle or display the error.
Execution Sample
Python
class MyError(Exception):
    pass

try:
    raise MyError("Oops!")
except MyError as e:
    print(e)
This code defines a new exception class, raises it, catches it, and prints the error message.
Execution Table
StepActionEvaluationResult
1Define class MyError(Exception)Class createdMyError is ready to use
2Enter try blockNo error yetProceed
3Execute raise MyError("Oops!")Raise exceptionException MyError("Oops!") raised
4Exception caught by except MyError as eCatch exceptionVariable e holds MyError("Oops!")
5Execute print(e)Print error messageOutput: Oops!
6End of try-except blockNo more codeProgram ends normally
💡 Exception raised and caught, program ends after handling
Variable Tracker
VariableStartAfter Step 3After Step 4Final
eundefinedundefinedMyError('Oops!')MyError('Oops!')
Key Moments - 3 Insights
Why do we inherit from Exception when creating MyError?
Inheriting from Exception makes MyError a proper error type that can be raised and caught, as shown in step 1 and step 3 of the execution_table.
What happens if we raise MyError but do not catch it?
If not caught, the program stops with an error message. Here, step 4 shows catching the error to prevent a crash.
Why do we use 'as e' in except MyError as e?
'as e' stores the caught exception in variable e, so we can access its message, as seen in step 4 and step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of variable 'e' after step 4?
ANone
Bundefined
CMyError('Oops!')
DException
💡 Hint
Check the variable_tracker row for 'e' after step 4.
At which step is the exception actually raised?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column in execution_table where 'raise' is mentioned.
If we remove the except block, what happens after step 3?
AProgram crashes with error
BProgram continues normally
CException is ignored
DException is caught automatically
💡 Hint
Refer to key_moments about what happens if exception is not caught.
Concept Snapshot
Create a new exception by defining a class inheriting Exception.
Raise it with 'raise MyError("message")'.
Catch it using try-except: 'except MyError as e:'.
Use 'e' to access the error message.
This helps handle errors clearly and safely.
Full Transcript
We start by defining a new exception class called MyError that inherits from Exception. This makes it a proper error type. Then, inside a try block, we raise this error with a message 'Oops!'. The program jumps to the except block that catches MyError and stores it in variable e. We print e, which shows the message. Finally, the program ends normally after handling the error. This process helps us create and manage custom errors in Python.

Practice

(1/5)
1. What is the correct way to create a custom exception class in Python?
easy
A. exception MyError(Exception): pass
B. def MyError(): raise Exception
C. class MyError(Exception): pass
D. class MyError: pass

Solution

  1. Step 1: Understand how to define a class inheriting Exception

    Custom exceptions must inherit from the built-in Exception class to behave like errors.
  2. Step 2: Check syntax correctness

    class MyError(Exception): pass correctly defines a class named MyError inheriting from Exception with pass inside.
  3. Final Answer:

    class MyError(Exception): pass -> Option C
  4. Quick Check:

    Custom exception class = class MyError(Exception): pass [OK]
Hint: Inherit from Exception to create custom errors [OK]
Common Mistakes:
  • Not inheriting from Exception
  • Using def instead of class
  • Wrong keyword like 'exception' instead of 'class'
2. Which of the following is the correct syntax to raise a custom exception named MyError?
easy
A. raise MyError()
B. throw MyError()
C. raise new MyError()
D. throw new MyError()

Solution

  1. Step 1: Recall the Python keyword to raise exceptions

    Python uses the keyword 'raise' to trigger exceptions, not 'throw'.
  2. Step 2: Check the syntax for raising a custom exception

    Correct syntax is 'raise MyError()' to create and raise the exception instance.
  3. Final Answer:

    raise MyError() -> Option A
  4. Quick Check:

    Raise custom error = raise MyError() [OK]
Hint: Use 'raise' keyword followed by exception instance [OK]
Common Mistakes:
  • Using 'throw' instead of 'raise'
  • Adding 'new' keyword like in other languages
  • Not calling the exception as a function
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. Oops!
B. MyError
C. Exception
D. No output

Solution

  1. Step 1: Understand the raise statement with message

    The code raises MyError with the message 'Oops!'.
  2. Step 2: Catch the exception and print its message

    The except block catches MyError as 'e' and prints 'e', which outputs the message 'Oops!'.
  3. Final Answer:

    Oops! -> Option A
  4. Quick Check:

    Exception message prints = Oops! [OK]
Hint: Exception instance prints its message string [OK]
Common Mistakes:
  • Printing exception class name instead of message
  • Not catching the exception properly
  • Expecting no output
4. Identify the error in this code snippet:
class MyError(Exception):
    pass

try:
    raise MyError
except MyError:
    print("Caught error")
medium
A. Incorrect exception name in except block
B. No error, code runs fine
C. Syntax error in class definition
D. Missing parentheses when raising MyError

Solution

  1. Step 1: Check how the exception is raised

    In Python, it is valid to raise an exception class without parentheses if it has no __init__ arguments.
  2. Step 2: Identify the problem in the code

    The code uses 'raise MyError' without parentheses, which is valid and does not raise an error.
  3. Final Answer:

    No error, code runs fine -> Option B
  4. Quick Check:

    Raising exception class without parentheses is allowed [OK]
Hint: Raising exception class without parentheses is valid if no arguments [OK]
Common Mistakes:
  • Omitting parentheses after exception name
  • Mismatching exception names in except block
  • Incorrect class syntax
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): self.code = 0 super().__init__(message)
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)
D. class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code

Solution

  1. Step 1: Understand how to extend Exception with extra attributes

    To add an error code, override __init__ and call super().__init__(message) to set the message properly.
  2. Step 2: Check which option correctly calls super().__init__ and stores code

    class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code calls super().__init__(message) and assigns self.code = code, correctly storing both.
  3. Final Answer:

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

    Call super().__init__(message) and store extra attributes [OK]
Hint: Call super().__init__(message) to set message, then add code [OK]
Common Mistakes:
  • Not calling super().__init__ for message
  • Assigning message without super call
  • Missing code attribute assignment