Home > database >  How do I do the exception without the traceback?
How do I do the exception without the traceback?

Time:11-17

I have the function which you can see in the picture. How do I only return the last line only, when the exception is raised, without the other lines: traceback.., file"" etc.

def division(k, m):
    try:
        k / m
    except TypeError:
        raise ValueError ('hey') from None
    return k/ m

Only want to return the: ValueError:hey

CodePudding user response:

Just put

import sys
sys.tracebacklimit = 0

Somewhere in your code. It will apply to all of your exception tracebacks though. I personally can't think of why I would do it, but knock yourself out!

CodePudding user response:

If you want to hide the exception, use pass instead of raising another exception.

def division(k, m):
    try:
        return k/m
    except TypeError:
        pass

If the exception occurs, this will return None by default. You could replace pass with a different return statement that returns whatever you want to use instead.

You shouldn't do the division again outside the try, since that will just get the error that you wanted to hide again.

  • Related