Exception doesnt display the message that a previously raised exception has - python

So i was trying to use Exception as e: but the variable e wouldnt display the message i previously assigned to it. Could you please help me?
SERVICE_CHARGE= 2
TICKET_PRICE = 10
tickets_remaining= 100
def calculate_price(number_of_tickets):
return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE
while tickets_remaining:
print "There are {} tickets remaining".format(tickets_remaining)
users_name=raw_input("What's your name? ")
try:
number_of_tickets=int(input("{}, how many tickets would you like to buy? ".format(users_name)))
if number_of_tickets>tickets_remaining:
raise Exception("Not enough tickets remaining")
except Exception as err:
print "Im sorry. {}. Please try again!".format(err)

This is because when you write Exception as e, e becomes an alias for the value stored in Exception, ie, e temporarily stores the value of Exception and then discards it(becomes undefined). You should use(you mention the variable e in your question but use err in your code):
except Exception:
print "Im sorry. {}. Please try again!".format(err)

Related

How to properly connect python mysql query using if-else and try-except for a delete function in task management system

I am currently working on a project task management system, and one of the functions is delete a category. I have tried this:
def deleteCategory():
try:
delcat='DELETE FROM Category WHERE cname = %s'
catname=str(input("Enter category name: "))
except HandleableErrors:
print("No categories yet!")
delcat = False
finally:
if delcat:
values=(catname,)
mycursor.execute(delcat, values)
db.commit();
print("Category deleted.")
else:
print("No category like that.")
but it still prints "Enter category name: " and "Category deleted" even when there are no categories. Can someone help me? Thank you.
This should work:
def deleteCategory():
try:
delcat = 'DELETE FROM Category WHERE cname = %s'
catname = str(input("Enter category name: "))
values = (catname,)
mycursor.execute(delcat, values)
db.commit()
print("Category deleted.")
except HandleableErrors:
print("No categories yet!")
delcat = False
except Exception as e: // change the Exception to the actual exception type you get when the operation is failing
print("No category like that.")
IMPORTANT NOTE: Change the Exception to the actual exception type you get when the operation is failing.

Try/except for check string in Python

I would like to use Try/ecept to check if a string is really a string. I made the following code:
nome = input('Name: ')
try:
if not nome.isalpha() or nome == '':
raise ValueError('Invalid!')
else:
print(f'Name {nome} valid.')
except ValueError as e:
print(f'Error: {e}')
But, I would like to do it without using the raise command, just try/except.
Can anyone help me? I thank you.
The only way to trigger an exception without raising it yourself is to attempt something invalid, such as this:
nome = input('Name: ')
try:
f = float(nome)
except ValueError as e:
print('Is alpha')
else:
print('Not alpha')
Here I try to convert the input to a float, and if there are any alpha characters in the value, it will raise the ValueError exception.

Exception In Python Doesn't Do Anything

I am beginner to python and I have doubt in one program when using try except part
I try to take input from user and add that number by 1 like if you enter 5 then 6 will be printed but if you enter string then except would come in role and print enter only number
I've written code but except is not working there, code is working like if I enter 5 then 6 gets printed but except statement is not working
Here is the code that I've written
def increment(num):
try:
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = int(input("enter your num: "))
a = increment(n)
print(a)
You would have to change to the following:
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The reason for that is that the exception was raised by the int() functions, because it couldn't convert your input to int. The call to int() was before the increment function. Therefore the exception was unhandled.
You tried converting the input to int before going into the try/except block. If you just put it in the try block it will work.
def increment(num):
try:
num = int(num)
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
You have to use the type conversion within the try block so that if num is not a number, the controller would move to expect portion.
The problem here is you are using type conversion outside of try-catch block.
Another point to note, convert e to string as a good practice.
Third point to note,the last line print(a) will itself cause trouble in cases of exception as you have returned nothing from the exception part and directly printed the error. Use a return statement in there else it would return None type and which itself will mess up the flow.
def increment(num):
try:
return int(num) + 1 #Updated Line
except Exception as e:
return "ufff error occurred :" + str(e) #Updated Line
n = input("enter your num: ")
a = increment(n)
print(a)
Might I recommend the following?
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occurred:", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The only difference here is that the attempt to convert the user's input to an int occurs within the try-except block, rather than outside. This allows the type conversion error to be caught and your message ("ufff error occurred: ...") to be displayed.
Edit: regarding your comment:
yes it worked out thanks everyone, but can anyone tell what should i have to do if i use int with input line what changes i've to make
Optionally, you could do the following:
def increment(num):
return num + 1
try:
n = int(input("enter your num: "))
a = increment(n)
print(a)
except Exception as e:
print("ufff error occurred:", e)
In this case, I would recommend removing the try-except block in the increment function, because you can safely assume that all values passed to that function will be numeric.
The only code that would raise an exception is the int(...) conversion - and it is not protected under a try/except block. You should put it under the try:
def increment():
try:
return int(input("enter your num: ")) + 1
except ValueError as e:
return f"ufff error occured: {e}"
print(increment())
You should always try to catch the narrowest exception. In this case, a ValueError.

How can my program know an exception from a separate method [duplicate]

This question already has answers here:
Manually raising (throwing) an exception in Python
(11 answers)
Closed 3 years ago.
I am writing a python program.
It calls a private method which has try...except... and returns a value.
Such as:
def addOne(x):
try:
a = int(x) + 1
return a
except Exception as e:
print(e)
def main():
x = input("Please enter a number: ")
try:
y = addOne(x)
except:
print("Error when add one!")
main()
The output is this when I entered an invalid input "f"
Please enter a number: f
invalid literal for int() with base 10: 'f'
I want to detect the exception in both main() and addOne(x)
So the ideal output may looks like:
Please enter a number: f
invalid literal for int() with base 10: 'f'
Error when add one!
Could anyone tell me how to do? Thanks!
Handling an exception prevents it from propagating further. To allow handling the exception also in an outer scope, use a bare raise inside the exception handler:
def addOne(x):
try:
a = int(x) + 1
return a
except Exception as e:
print(e)
raise # re-raise the current exception

how to catch error(200)

I'm trying to get input from user, until he press ctrl-c. yet, I can't catch the
error, I think it has something to do with sklearn (I imported it for the rest of the code)
this is the code:
try:
while(True):
i+=1
put = input("\tEnter name of feature number " + str(i) +":\t")
features.append(put)
except KeyboardInterrupt:
print("\n\tFeatures Added!")
sleep(SLEEP)
return None
except:
exit("\nError has occurred, please come back later...")`
Fix your indentation as the following:
try:
while(True):
i+=1
put = input("\tEnter name of feature number " + str(i) +":\t")
features.append(put)
except KeyboardInterrupt:
print("\n\tFeatures Added!")
sleep(SLEEP)
return None
except:
exit("\nError has occurred, please come back later...")

Categories