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.
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:
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!")
Related
Is there a way to make an exception for the same error if the previous exception raises an error? I know this example doesn't make sense, but it's the easiest way to demonstrate what I mean. For example:
import string
a = input('')
try:
print(str(int(a)+1))
except ValueError:
print(string.punctuation.index(a))
Is there a way to work it so if it isn't a number, it goes to except ValueError to run if it is in string.punctuation, but then if that raises a ValueError then it goes to another except ValueError to say that it isn't a number or symbol? etc. something like this but in a code that works:
import string
a = input('')
try:
print(str(int(a)+1))
except ValueError:
print(string.punctuation.index(a))
except ValueError:
print('Not a number or symbol!')
You'll need another try block within the except to catch the second ValueError.
import string
a = input() # no need for an empty arg
try:
print(int(a) + 1) # no need for explicit str conversion
except ValueError:
try:
print(string.punctuation.index(a))
except ValueError:
print('Not a number or symbol!')
I am trying to write a program which accepts multiple inputs from user and do whatever is required but i don't want the program execution stop when user gives some error in the input rather i would like that line of program to be repeated again and again until the user gives a valid input or cancel the operation.
For example i have the following piece of program :-
# Error handling
i=int(eval(input("Enter an integer: " )))
print(i)
Now if the user enters a string following error is occurs :
Enter an integer: helllo
Traceback (most recent call last):
File "C:/Users/Gaurav's PC/Python/Error Management.py", line 2, in <module>
i=int(input("Enter an integer: " ))
ValueError: invalid literal for int() with base 10: 'helllo'
HERE, I want Python to re-run the line 2 only for a valid input until user inputs a correct input or cancel the operation and once a correct input is passed it should continue from line 3, How can i do that?
I have tried a bit about it using try and except statement but their are many possible errors and i cannot find a way to run that line again without re-writing it in the except block and that too works for one error or the number of times i copy the same code in the except block.
You can put it in a while loop and check to see if an an input is an integer or not:
def is_integer(s):
try:
int(s)
return True
except ValueError:
return False
while True:
i = input("Enter an integer: " )
if is_integer(i):
print(i)
break
Try :
while True:
try:
i = int(input("Enter number : "))
break
except:
continue
Or you can use pass instead of continue.
TL;DR: Why are my exceptions triggering only in certain situations, despite the fact that it is the same error?
The code successfully catches a NameError with an all numerical argument. So if someone mistakenly inputs a number instead of an operator, it gives them the correct exception error message. However, my code fails to catch other exceptions, and I'm unsure why.
For example:
print(better_calc(5, 5, 5))
This returns the desired exception message of
5 5 5 = Error: Name error. Please check your input
However, it does not catch other errors. Instead, it terminates the programme.
For example,
print(better_calc(5, g, 5))
This returns ''NameError: name 'g' is not defined'', without triggering the exception or the exception message.
Similarly
print(better_calc(5, *, 5))
This returns ''SyntaxError: invalid syntax'', without triggering the exception or the exception message.
I realize that if I included quotation marks on the operator, that the code would work, however, my goal is to trigger the exceptions.
def better_calc(num1, op, num2):
try:
if op == "+":
result = num1+num2
elif op == "-":
result = num1-num2
elif op == "*":
result = num1*num2
elif op == "/":
num1/num2
except NameError:
print(f"Error: Name error. Please check your input")
except UnboundLocalError:
print(f"Error: Value error. Please check your input")
except SyntaxError:
print(f"Error: Syntax Error. Please check your input")
print(num1, op, num2, "=")
return result
print(better_calc(5, 5, 5))
Just to consolidate the answers already given in the comments, try/except blocks can only handle errors that are raised between the try: and the first except block.
try:
# raised exceptions in this block can be caught
foo = "bar"
except FooError:
# catches a raised FooError but any exceptions raised here are
# outside of the try block and will not be handled. Another try/except
# block could be added here to catch these exceptions
pass
except Exception as e:
# a trick to log exceptions but then let the exception run
print(e)
raise
The call to the function print(better_calc(5, g, 5)) is outside of the function's try block and will not be caught.
And syntax errors like print(better_calc(5, *, 5)) keep the program from even running, which is definitely outside of the function's try block.
If I've defined a class that takes in two or more parameters:
class SomeObject:
def __init__(self, int_param, str_param):
#if parameters are wrong type:
raise TypeError("wrong type")
...
if (__name__ == "__main__"):
try:
invalid_obj = SomeObject('two', 'string')
print (invalid_obj)
except TypeError as e:
print (e)
it'll print "wrong type", but is there a way for it to also return which argument is raising the exception? Can I get the output to be:
"wrong type 'two'"
? I've tried print (e.args), print (repr(e)), and simply print(e) but the invalid argument never gets printed. Just wondering if this is possible, thank you.
edit: It works with a custom exception type, and if I list each parameter being tested individually - I also have ValueError catching for both the int_param and str_param as well, so I wanted to see if I can condense the if statements to just:
#if params not right type:
raise TypeError
#if params contain invalid value:
raise ValueError
and still get it to return the specific invalid argument that's causing the error. I'll definitely keep the custom Exception type in mind for future assignments; unfortunately for this one the instructor has "raise TypeError" and "raise ValueError" as requirements for full marks. She doesn't require the invalid argument to be returned though, that was just me being curious if I could manage it. I ended up with:
#if int_param not int:
raise TypeError("int_param {0} given is invalid type".format(int_param))
#if str_param not int:
raise TypeError("str_param {0} given is invalid type".format(str_param))
#if int_param is an invalid value:
raise ValueError("int_param {0} given is invalid value".format(int_param))
....
and so on. If anyone can see a cleaner way to do this (without a custom Exception type), please let me know!
You can make your own exception:
class SomeObjectException(TypeError):
def __init__(self, msg, which):
TypeError.__init__(self, msg)
self.which = which
Then:
class SomeObject:
def __init__(self, int_param, str_param):
#if parameters are wrong type:
raise SomeObjectException("wrong type", int_param)
And:
if (__name__ == "__main__"):
try:
invalid_obj = SomeObject('two', 'string')
print (invalid_obj)
except SomeObjectException as e:
print (e, e.which)
Also see proper way to declare custom exceptions in modern Python.
class SomeObject:
def __init__(self, int_param, str_param):
if type(int_param) != int:
raise TypeError("int_param: wrong type")
if type(str_param) != str:
raise TypeError("str_param: wrong type")
Maybe you should look for the traceback module.
instead of raise TypeError("wrong type") wrap traceback.print_exc() in try, except and see if that's what you looking for.
I am doing some practice problems from online with python and I have a question about how to stay in a script if an error is raised. For example, I want to read in values from prompt and compare them to a set integer value inside the script. The only problem is that when someone enters something other than a number 'int(value)' (ex. value = 'fs') raises an error and exits the script. I want to have it so if this happens I stay inside the script and ask for another value to be entered at the prompt.
Use try/except.
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
success = false
while not success:
try:
value = raw_input('please enter an integer')
int(value)
success = true
except:
pass
How about catching it?
try:
a = int('aaa')
except ValueError:
print('Still working')
Ah, you just want to catch the error (as long as it isn't final): see http://docs.python.org/tutorial/errors.html for details? Or are you looking for something else?
for this, you use try... except as explained in the python documentation
Read up on the try: except: idiom here
if you are doing it as a function you can do it as a decorator of the function
def retry(func):
def wrapper(*args,**kwargs):
while True:
try:
return func(*args,**kwargs)
except Exception as e:
print(f"{e} running again") # or simply pass
return wrapper
#retry
def myfunction():
if badthinghappend:
raise Error
return something