Home > Software design >  How to remove additional text while raising an error in python
How to remove additional text while raising an error in python

Time:10-19

So i made some random stuff:

def println(text: str) -> str:
    print(text)
    if not type(text) == str:
        raise TypeError("Text not string type")

println("Hello, World!")

Now, when i put a string inside the println() function it works perfectly fine. But if i put an integer inside the println() function it raises a TypeError with the location where it's coming from like this:

Traceback (most recent call last):
  File "c:\Users\???\Desktop\leahnn files\python projects (do not delete)\Main files\main.py", line 6, in <module>
    println(1)
  File "c:\Users\???\Desktop\leahnn files\python projects (do not delete)\Main files\main.py", line 4, in println
    raise TypeError("Text not string type")
TypeError: Text not string type

It does raise the TypeError but it's saying where it's coming from. I was wondering if you can just remove the location it's coming from and just say:

TypeError: Text not string type

If i just do:

def println(text: str) -> str:
    print(text)
    if not type(text) == str:
        print("TypeError: Text not string type")

It's gonna print out the integer that is inside the println() function and it's gonna print the TypeError after the integer inside the println() function is done executing. Is it possible?

CodePudding user response:

You can handle exception with try-except clause and in except just print error message. See https://docs.python.org/3/tutorial/errors.html#handling-exceptions

try:
    println(1)
except TypeError as err:
    print(err)
  • Related