2013-11-15 12 views
1

我在课堂中遇到异常问题。如果可能的话,我希望它返回到我的主脚本,或任何可以避免我的程序崩溃的解决方案。我会告诉你代码。问题与类的异常,如何让它返回主脚本?

这里的主脚本:

from requestnew import requestNew 


def chooseCountry(): 
    countryc = input("Enter which country your city is in(in english): ") 
    rq.countrychoice.append(countryc) 

def chooseCity(): 
    cityc = cityc = input("Enter the name of the city: ") 
    rq.citychoice.append(cityc) 

def makeForecast(): 
    try: 
     for day in rq.data['forecast']['simpleforecast']['forecastday']: 
      print ("Country: ", rq.countrychoice[-1], "City: ", rq.citychoice[-1]) 
      print (day['date']['weekday'] + ":") 
      print ("Conditions: ", day['conditions']) 
      print ("High: ", day['high']['celsius'] + "C", '\n' "Low: ", day['low']['celsius'] + "C", '\n') 
    except Exception as e: 
     print ("\nHave you typed in the correct country and city?\nBecause we got a" ,'"',e,'"', "error\nplease try again!") 
     return menu 


if __name__ == '__main__': 
    """Introducion""" 
    print ("\nThis program lets you see a weather forecast for your choosen city.") 
    rq = requestNew() 

    while True: 
     try: 
      print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n") 
      menu = int(input("\nPress 1 for country\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n")) 
      if menu == 1: 
       chooseCountry() 
      elif menu == 2: 
       chooseCity() 
      elif menu == 3: 
       rq.forecastRequest() 
       makeForecast() 
      elif menu == 4: 
       print ("\nThank you for using my application, farewell!") 
       break 
      elif menu >= 5: 
       print ("\nYou pressed the wrong number, please try again!") 
     except ValueError as e: 
      print ("\nOps! We got a ValueError, info:", e, "\nplease try again!") 
      continue 

这里是我的类代码:

import requests 
import json 

class requestNew: 

    def __init__(self): 
     self.countrychoice = [] 
     self.citychoice = [] 

    def countryChoice(self): 
     self.countrychoice = [] 

    def cityChoice(self): 
     self.citychoice = [] 

    def forecastRequest(self): 
     try: 
      r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + self.countrychoice[-1] + "/" + self.citychoice[-1] + ".json") 
      self.data = r.json() 
     except #? 

正如你可以看到上面我用的def forecastRequest(self):异常。问题是我不知道哪个异常以及如何正确返回以避免任何程序崩溃。

如果你看看我的主脚本,你可以看到我有while True:来循环菜单中的所有内容。

程序中的所有内容除了按3之外都能正常工作; elif menu == 3:没有从def chooseCountry():选择国家或从def chooseCity():选择城市。 这是因为我在我的课堂上使用了一个列表,然后像这样在def forecastRequest(self):中打印它; countrychoice[-1]从输入中获取最后附加的列表项。当我在菜单中按3而没有选择国家或城市时,列表将为空。

我的问题是,有什么办法让except #?def forecastRequest(self):返回用户到我的主脚本菜单?或者当我尝试提出请求时,如果列表为空,还有其他方法可以避免崩溃程序吗?

对不起,我的英语很抱歉,如果我的解释很混乱,我尽我所能,让它尽可能相对容易理解。

回答

1

如果你想控制返回到主循环,赶在主回路异常:

elif menu == 3: 
    try: 
     rq.forecastRequest() 
    except IndexError: 
     # self.countrychoice[-1] will raise an IndexError if self.countrychoice is empty 
     # handle error 
    else: 
     makeForecast()     
+0

呸我太专注它必须是在类,这个完美的作品,非常感谢你许多! @unutbu – Bondenn