2010-09-13 96 views
2

在例外情況下如何處理變量的範圍處理?我想這將是語言特定的,任何特定語言的答案都將不勝感激。至少也許是大的? C++, python, Java。這就是我的意思是:如何在例外情況下處理變量範圍

蟒蛇


     try: 
      for k, v in map.iteritems(): 
       cnf.conf.set(section, k, v) 
      for i, j in map2.iteritems(): 
       dosomethingelse() 
       for m in range(10): 
        morestuff() 
     except SpecificError: 
      vars = (k, v, i, j, m) 
     finally: 
      vars in scope #? 

或者更復雜的東西,比如嵌套塊:


    try: 
     try: 
      for k, v in map.iteritems(): 
       cnf.conf.set(section, k, v) 
      for i, j in map2.iteritems(): 
       dosomethingelse() 
       for m in range(10): 
        morestuff() 
     except SpecificError: 
      vars = (k, v, i, j, m) 
    except: 
     vars in scope #? 

回答

1

在java中,我相信你能做到以下幾點:

try { 
String s = "Hello, finally!"; 
... 
} 
finally { 
System.out.println(s); 
} 

你必須做:

String s = null; 

try { 
s = "Hello, finally!"; 
... 
} 
finally { 
System.out.println(s); 
} 

換句話說,變量的範圍限於它所在的塊。

HTH

相關問題