How to create a class/function that can make any error

I’m wondering, how can I create a class/function that can create an error that gets its name and message from arguments?
I want something like this:

def CreateError(error_name, error_message):
  return SomeError(f'{error_name}: {error_message}')

raise CreateError('TypeError', 'expected type \'str\' but got type \'int\'')

Why not just raise a TypeError?

It’s recommended to do "expected type 'str' but got type 'int'" to avoid backslashes for readability.


I was just showing an example so people would understand what I’m saying

Would you have a very large pool of these errors, or would a few be sufficient?


I’m just wondering how to do it


def create_error(error_name, error_message):
    exec(f'class {error_name}(Exception):\n    def __init__(self):\n        super().__init__("{error_message}")')

create_error('Error', "expected type 'str' but got type 'int'")
raise Error()

Lmk if it works Ig

Edit: no it doesn’t work

You could try something similar to it Ig

idk usually i just use sys.exit for custom error handling

import sys

def CreateError(error_name, error_message):
    sys.exit(f"{error_name}: {error_message}")

7 posts were split to a new topic: What should you use for custom errors in Python?

If I got it right you want to create an error with a dynamic name?

You can create a class for that

For example:

def create_error(error_name, error_message):
    return type(error_name, (Exception,), {"__init__": lambda self: super().__init__(error_message)})

    raise create_error('MyError', 'An error occurred')()
except Exception as e:
    print(f'Caught an exception: {e.__class__.__name__}: {str(e)}')

So create_error will be a new class. The init will be making the call. The type function need 3 things (name, bases (tuple) and dict)

So type here will be:


1 Like

this is what i came up with:

def create_err(err_name, err_msg):
    raise err_name(err_msg)

create_err(TypeError,'expected type \'str\' but got type \'int\'')

you just pass the error as a param and raise it

That’s the same thing as creating an error

if you want a custom python based exception then you inherit from Exception in a new class like so:

class MyError(Exception):
    def __init__(self, err_msg):

raise MyError("error message")
1 Like

Came up with this after a bit of tinkering, tested and works well:

class Error(Exception):

class errorBase(Error):
    def __init__(self, details = None):
        self.expression = details

def makeError(name: str, message: object) -> None:
    abc = type(f'error{name}', (errorBase,),{})
    abc.__name__ = name
    raise abc(message)
1 Like

The error has a prefix (__main__)


There is that. I’ll fiddle with it a bit more and see if I can remove that.

@SnakeyKing How does this work for you?

class errorBase(Exception):
    def __init__(self, details = ""):
        self.expression = details

def makeError(name: str, message: object) -> None:
    abc = type(f'error{name}', (errorBase,),{})
    abc.__module__ = "builtins"
    abc.__name__ = name
    raise abc(message)

I could use Exception
btw I wanted to return an error

def CustomError(name: str, message: object):
    error = type(f'{name}', (Exception),{})
    error.__module__ = "builtins"
    error.__name__ = name
    return error(message)

raise CustomError('Error Name', 'error message')

Using that, I compressed the function a bit more (You can now (optionally) specify a module to raise from too!):

def makeError(name: str, message: object, module: str = "builtins") -> None:
    raise type(name, (Exception,),{"__module__": module, "__name__": name})(message)
# Option 2:
def makeError(name: str, message: object, module: str = "builtins") -> None:
    return type(name, (Exception,),{"__module__": module, "__name__": name})(message)


makeError(module="hi", name="there", message="friend")
# or
makeError("there", "friend", "hi")
# or
makeError("SomeError", "Some message")
# Option 2:
raise makeError(module="hi", name="there", message="friend")
# or
raise makeError("there", "friend", "hi")
# or
raise makeError("SomeError", "Some message")

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.