如何使用try / catch / finally确保函数返回值?

时间:2010-11-03 10:39:48

标签: c#

如何使用try / catch / finally确保函数返回值?

我正在从Excel工作表中读取单元格。有时解析操作并不总是有效。如果操作失败,我需要返回0,如果,无论如何。

try
{
  //1. read cell value from excel file
  //2. get the value, convert it as string, and
  //3. return it 
}
catch {}
finally {}

感谢您的帮助

7 个答案:

答案 0 :(得分:3)

这就是我这样做的方式,有一个像这样的返回值:

   string result = 0;

    try
    {
      //1. read cell value from excel file
      //2. get the value, convert it as string, and
      //3. return it 
      result = cellValue;
    }
    catch {}
    finally {}

    return result;

虽然我更喜欢让它抛出异常,所以我知道出现了问题,因为我肯定知道当你读取的单元格值为0时,它不会像你的情况那样起作用吗?

这可能是一个更好的解决方案,并与.NET保持一致:

public bool TryParseCell(Cell cell, out string parsedValue)
{
   try
   {
      parsed value = ....; // Code to parse cell
      return true;
   }
   catch
   {
      return false;
   }
}

答案 1 :(得分:1)

String value;
try
{
  //1. read cell value from excel file
  //2. get the value, convert it as string
// no return here!
}
catch ...{
// exception hadling
   value = "0";
}
finally {}
return value;

答案 2 :(得分:1)

public int myFunction()
{
    int ret = 0;
    try
    {
        // obtain ret here from Excel
    }
    catch(System.Exception _e)
    {
        // an error occured, ensure 'ret' is 0
        ret = 0;
    }
    finally
    {
        // any cleanup code you must do, success or failure, e.g. Close excel
    }
    return(ret);
}

答案 3 :(得分:1)

try
{
  //1. read cell value from excel file
  //2. get the value, convert it as string, and

 convertOK=true;
  //3. return it 


}
catch {}
finally {}

if(!convertOK) return 0;

答案 4 :(得分:1)

以下内容应该有效:

int returnVal = 0;
try
{
// Do something useful which sets returnVal
}
catch()
{
// Ex Handling here 
}
finally
{
// Any clean up here
}
return returnVal;

答案 5 :(得分:1)

public int returnValue()
    {
    int returnValue=0;
    try
    {
       returnValue = yourOperationValue;
    }
    catch {}
    finally 
    {

    }
  return returnValue;

    }

答案 6 :(得分:1)

您不需要finally

int retValue;

try
{    
    // do something
    retValue = something;
    return retValue;    
}
catch (ApplicationException ex) // or just Exception
{    
    return 0;    
}