如果在try / except块中有其他代码帮助

时间:2012-05-04 16:00:20

标签: python python-2.7

SomeDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}
try: 
    result = ""
    theKey = raw_input("Enter some key: ")
    val = someDict[theKey]
    except keyErrorr:
        result "hello"
    else:
        result = result + "" + "done"
    print result 

我理解您可以插入的try块和代码以尝试查看出现的错误,然后可以通过except块捕获错误。我试图找出在try和except块中插入if / else的最佳方法,以解决此代码中出现的相同键错误。我想我可以替换try,除了使用If / else或者可以在try和else中添加if / else。任何有关如何将if / else插入此代码以获取密钥错误的帮助将不胜感激。所以基本上我想在try和except块中添加一个if / else代码以获得相同的键错误。

 SomeDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}
    try: 
        result = "" #could i insert something like if result == "" : #for this line?
        theKey = raw_input("Enter some key: ")
        val = someDict[theKey]
        except keyErrorr:
            result "hello"
        else:
            result = result + "" + "done"
        print result 

3 个答案:

答案 0 :(得分:2)

一个合理的选择是初始化result = None,然后测试if result is None:

最好使用None而不是空字符串,因为有一天你可能希望字典值为空字符串,而且对于代码的随意读者来说,None可能更清楚。

您也可以跳过try-except,并使用if theKey in someDict:

答案 1 :(得分:1)

你可以添加另一个,除了没有规范它应该处理什么异常。

try:
   # do something
except KeyError:
   # do something because of the Keyerror
except:
   # do what you need to do if the exception is not a KeyError

答案 2 :(得分:0)

someDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}   # corrected dict name
result = ""
theKey = raw_input("Enter some key: ")
try:                    # just try the code where the error could be
    val = someDict[theKey]
except KeyError:        # corrected exception name and indent level
    result = "hello"    # corrected syntax
else:                   # corrected indent level
    result = result + "" + "done"       # why add "" ?
print result 

这对你有用吗?