0

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • What do you want it to return instead when the error happens? – Barmar Nov 16 '21 at 19:11
  • You're not returning the exception, it is being raised. It is the interpreter that does you the "favor" of printing the traceback when it encounters an uncaught exception. Maybe this may be of help to you, https://stackoverflow.com/questions/17784849/print-an-error-message-without-printing-a-traceback-and-close-the-program-when-a? – frippe Nov 16 '21 at 19:14

2 Answers2

1

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!

Peter White
  • 328
  • 2
  • 8
0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612