2014-12-26 78 views
0

我試圖從函數返回一個值。函數WcfProvider.MetalsPrices可能會引發異常。我想避免它。不能跳出finally塊

public IEnumerable<PriceOfMetal> GetPrice(int id, DateTime time) 
{ 
     bool condition = false; 
     DateTime timenew = time.AddDays(-1); 

     var allPrice = from c in db.PriceOfMetal 
         select c; 

     foreach (var i in allPrice) 
     { 
      if (i.Date.Date == timenew.Date && i.ListOfMetaL_Id==id) 
      { 
       condition = true; 
      } 
     } 

     try 
     { 
      if (condition == false) 
      { 
       var price = WcfProvider.MetalsPrices(id, time, time).Tables[0].AsEnumerable() 
        .Select(
         a => 
          new PriceOfMetal() 
          { 
           Date = a.Field<DateTime>("Date"), 
           ListOfMetaL_Id = a.Field<int>("MetalId"), 
           Value = a.Field<System.Double>("Price") 
          }) 
        .ToList().Single(); 

       db.PriceOfMetal.Add(price); 
       db.SaveChanges(); 
      } 
     } 
     finally 
     { 
      var all = from c in db.PriceOfMetal select c; 
      return all; 
     } 

我想最後返回塊的值。可能嗎?我收到一個錯誤。

+3

錯誤說的是什麼? – Gjeltema

回答

4

如果內部發生異常,您必須決定您的函數是否應正常返回或異常返回。

如果異常(你的來電者會看到除外):

try { 
    // do stuff 
    return answer; 
} 
finally { 
    // cleanup stuff 
} 

如果正常,則需要處理該異常:

try { 
    // do stuff 
} 
catch { 
    // recover stuff   
} 
// cleanup stuff 
return answer; 

你永遠不能把一個return聲明中finally塊,因爲finally在存在未捕獲的異常時運行,並且由於未捕獲的異常而導致函數結束(異常)時,則不會有返回值。

2

你可能需要這樣的

try 
{ 
    return here 
} 
catch(Exception ex) 
{ 
    // Catch any error 
    // re throw if you choose, 
    // or you can return if you choose 
    return here 
} 
finally 
{ 
    // allways do whats here 
} 

的模式,您可能需要閱讀一對夫婦的網頁在這裏:try-catch-finally (C# Reference)


只是建立在這個多一點,試想一下,如果我們可以在最後一個塊內返回

您可能會有一段令人討厭的代碼,如下所示,這可能會令人困惑

try 
{ 
    return 10; 
} 
catch (Exception e) 
{ 
    return 20; 
} 
finally 
{ 
    return 30; 
} 

編譯器會返回什麼?

+0

它不起作用 – Denis

+0

@Denis雞姦,請更新您的問題與一些更多的細節,它不是很明顯你問什麼,或者錯誤是什麼 –

0

我很抱歉地說這個,但你的問題很模糊,很難回答。你的代碼看起來很複雜。無論如何,這是假期。也許下面會幫助你。雖然沒有保證。

public IEnumerable<PriceOfMetal> GetPrice(int id, DateTime time) 
{ 
    DateTime timenew = time.AddDays(-1); 

    var allPrice = from c in db.PriceOfMetal 
        select c; 
        where c.Date.Date == timenew.Date 
        and c.ListOfMetal_Id == id 

    if (!allPrice.Any()) 
    { 
     try 
     { 
      var price = WcfProvider.MetalsPrices(id, time, time).Tables[0].AsEnumerable() 
         .Select(a =>new PriceOfMetal 
         { 
          Date = a.Field<DateTime>("Date"), 
          ListOfMetaL_Id = a.Field<int>("MetalId"), 
          Value = a.Field<System.Double>("Price") 
         }) 
         .ToList().Single(); 

      db.PriceOfMetal.Add(price); 
      db.SaveChanges(); 
     } 
     catch 
     { 
      // Eating exceptions like this is really poor. You should improve the design. 
     } 
    } 
    return db.PriceOfMetal; 
}