我正在尝试从函数返回一个值。该函数WcfProvider.MetalsPrices可能会抛出异常。我想避免它。
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;
}
Run Code Online (Sandbox Code Playgroud)
我想最终返回块的值。是否可以?我收到一个错误。
如果内部发生异常,您必须决定您的函数是应该正常返回还是异常返回。
如果异常(您的调用者将看到异常):
try {
// do stuff
return answer;
}
finally {
// cleanup stuff
}
Run Code Online (Sandbox Code Playgroud)
如果正常,则需要处理异常:
try {
// do stuff
}
catch {
// recover stuff
}
// cleanup stuff
return answer;
Run Code Online (Sandbox Code Playgroud)
你永远不能把一个return语句放在一个finally块中,因为finally在有未捕获的异常时运行,当你的函数由于未捕获的异常而结束(异常)时,没有返回值。
| 归档时间: |
|
| 查看次数: |
2474 次 |
| 最近记录: |