How to remove “raise ValueError()” from the traceback output?

Here is an example:

def f(x):
    if x == 0:
        raise ValueError("Input is zero")
    return

print(f(0))

which results in

Traceback (most recent call last):
  File "..\file.py", line 25, in <module>
    print(f(0))
  File "..\file.py", line 22, in f
    raise ValueError("Input is zero")
ValueError: Input is zero

I want line 5, raise ValueError("Input is zero"), removed from the output.
I do not support try and except, so I will be grateful if you do not implement them in your answer(s). Remove raise if you wish, and use another method.

Here is an example made by a standard library:

from math import factorial as f
print(f(-1))

Output:

Traceback (most recent call last):
  File "..\file.py", line 29, in <module>
    print(f(-1))
ValueError: factorial() not defined for negative values

I assume (this part of) math is not using raise.

  • I honestly have no idea at all about your expected behaviour

    – 

  • 1

    What difference does it make if the calling code is displayed in the traceback? You’re probably seeing an exception being raised in C in the second example

    – 




  • If you don’t want the line that raises the exception to be shown in the traceback, either you have to catch and modify the traceback, or your function has to be implemented in native code (C/C++) and then called from Python; this is why, in your second example, the exception itself is shown but not a raise ValueError(). Because factorial is implemented in native code, when the exception is raised, the stacktrace won’t show the C/C++ code that raised it, since it only shows and knows about Python code.

    – 




  • @roganjosh I am trying to prettify the traceback. That line is useless to me because I get the same report below it.

    – 

  • 1

    @JonSG As I have mentioned in the question, I want only and only line 5, raise ValueError("Input is zero"), removed from the traceback.

    – 




Leave a Comment