Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try and except
#1
Hi!

Doing homework for programming class, having problems with try-except. So the program works fine, it opens the txt file and searches for the correct city, however, the except line does not work. So if you enter a name of city that is not in the txt file of cities it should go to the except line and print "wrong" but it doesn't. Could anybody help pls? Thanks! **wall**

city = raw_input ("Enter the name of the city: ")
ffile = open ("cities.txt")
try:
for line in ffile:
if line.startswith (city):
d1 = line.split (".")
d2 = d1 [1]
d3 = int(d2)
print d3
except:
print "wrong"
Reply
#2
try/except is designed to handle errors- your except code will only run if your code has an error. You can check this by taking out the try/except to see what happens. I'm not positive, but it looks like your code won't cause any errors if the city isn't included. 
Do you have to use try/except?
Reply
#3
Yes, I do have to use try-except. The point is that if the user enters the name of the city incorrectly (e.g. Londdon not London) and thus such name cannot be found in ffile, the program does not crash but says to the user that this is invalid name of the city.
Reply
#4
Quote:
 if line.startswith (city): 

That line doesn't throw an error if it doesn't find the substring, it just returns False.  try/except catch errors, full stop.  If there's no error, an except block will not run.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020