1

I wanted to know how to hide errors in python: Let's say I made a calculator and then typed:

if number1 != int:
     print("NaN")

But it will print this message and give out the error which is built into python which is: Traceback (most recent call last):

but how do I hide this Traceback error and only show the error message which is "NaN"

Thank you for the answer.

1
  • 1
    if number1 != int: makes no sense. What exactly are you trying to do? Commented Aug 2, 2021 at 13:24

2 Answers 2

2

Even though you are talking about try...except, the following statement makes no sense.

You telling python to compare 1 to data type int

if number1 != int: print("NaN")

If you want to check a particular data type, use isinstance(<variable>,<data type>)

if isinstance(number1,int): print("NaN")

You can use try...except method to catch various errors:

try:
    number1=int(input("Enter a number: "))
    ...
except ValueError:
    print("NaN")

Note that this will catch only ValueError. If you want to catch all errors, use except Exception or except:

Sign up to request clarification or add additional context in comments.

2 Comments

Ohk thank you so much! Sorry for the incorrect meaning in the code.
@kronox, no problem
0

To "hide" a Error message (NameError) you can try the following, but this is only because number1 is not defined:

try:
    if number1 != int: print("NaN")

except NameError:
    print("Error is hidden!")

except:
    print("Catch all other Exceptions!")

For more see the following link.

I think you want to check if the inserted numer is not an integer. This can be done with the following code:

number = "asdf"

if type(number) != int: 
    print("NaN")

else:
    print("Valid number!")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.