Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用try/catch/finally确保函数返回值?_C# - Fatal编程技术网

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

C# 如何使用try/catch/finally确保函数返回值?,c#,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 {} 感谢您的帮助我就是这样做的,返回值如下: String value;

如何使用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 {}

感谢您的帮助

我就是这样做的,返回值如下:

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;
   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;
   }
}

以下方面应起作用:

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

您最终不需要

int retValue;

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

您是否有完成任务(例如关闭文件等)?此方法不应像现在这样编译。编译器确保每个可能的路径都返回一些内容。您是否还有其他未告诉我们的退货声明?=)你说得对。我省略了一些代码。当然,您应该在catch处理程序中将值设置为“0”,而不是从中返回?这也是可能的,但我喜欢在方法中使用最小返回计数。它增加了代码的可读性和清晰性。为了与.Net真正一致,签名可能应该是public bool TryParseCell(Cell Cell,out string parsedValue)@BurningIce:K,仅适用于您;)但是如果你真的想学究气,那应该是Cell.TryParse,虽然我认为这更清楚地解释了这一点,但如果没有对象的实例,你就无法创建扩展方法:/
int returnVal = 0;
try
{
// Do something useful which sets returnVal
}
catch()
{
// Ex Handling here 
}
finally
{
// Any clean up here
}
return returnVal;
public int returnValue()
    {
    int returnValue=0;
    try
    {
       returnValue = yourOperationValue;
    }
    catch {}
    finally 
    {

    }
  return returnValue;

    }
int retValue;

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