0
def println(text: str):
    try:
    print(text)
    if not type(text) == str:
        raise TypeError(f"argument \"text\" should be type \"str\". not type \"{type(text)}\"".)
    except TypeError as err:
         print(err)

This works fine and it says:

argument "text" should be type "str". not type "<class 'int'>".

but I don't see what line it's coming from. It's coming from line 4 and it doesn't say the line where the error is coming from. This makes it hard and frustrating to debug errors.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Rydex
  • 395
  • 1
  • 3
  • 9
  • 4
    If you don't catch the error, the interpreter will happily show you the full traceback (which includes the line numbers). Throwing an error just to catch it in the same scope doesn't seem like the best implementation. Also `print(text)` works happily with things that aren't strings, so you print _then_ throw (and then print) the error. – jonrsharpe Oct 19 '21 at 13:43

1 Answers1

1
import traceback
traceback.print_exc()

will use the same default traceback formatting the interpreter uses for uncaught exceptions.

Or, better yet, don't catch the exception at all and let it be handled elsewhere? If you do need to wrap an exception to change its type or message, you can do

except SomeException as exc:
    raise RuntimeError("a thing broke") from exc

which will retain the original exception and traceback.

AKX
  • 152,115
  • 15
  • 115
  • 172