Python Forum

Full Version: multi-line messages in raised exceptions?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
many of my functions accept many keyword arguments like:
def callme(*args,**opts):
    ...
they then have code to pop off the known keywords like:
def callme(*args,**opts):
    foo = opts.pop('foo',default_foo)
    bar = opts.pop('bar',default_bar)
    ...
then they check to see if any keywords are leftover like:
def callme(*args,**opts):
    foo = opts.pop('foo',default_foo)
    bar = opts.pop('bar',default_bar)
    if opts:
        raise ValueError(f'unknown keywords: {", ".join(x for x in opts.keys())}')
    ...
is it possible to output a multi-line message, one line for each keyword in this example, in the raised exception? i would also like to check the arguments, too, and combine messages related to this, too.
You know, it probably would have been less effort to just try to raise a multiline exception message than to type out a whole post explaining your function design and why you want to do it.

In fact, I'm sure it would have been, because I tried it and it took less effort than typing this post up.
do you already have a process capturing exceptions?
if you don't know what exceptions are being thrown, you can use a general capture
You can replace with exception names as indentified
try:
    ...
except:
    print("Unexpected error:", sys.exc_info()[0])
    print(f"Args:")
    for arg in args:
        print(f"{arg}")
    raise
i'm not trying to capture the exception. it's a function. the caller that imported it may want to capture it. but if not, i want to have a line per keyword that remains in the dictionary.