开发者

How can I use try/catch/finally to make sure that the function will return value?

How can I use try/catch/finally to make sure that the function will return value?

开发者_高级运维I'm reading cells from an Excel sheet. Sometimes the parsing operation is not always working. I need to return 0, if, for whichever reason the operation fails.

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

Thanks for helping


This is how I do it, by having a return value like so:

   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;

Although I prefer to let it throw exceptions so I know something has gone wrong as I'll know for sure it didn't work as what happens in your case when the cell value read is 0??

This may be a better solution, and is consistent with .NET:

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


You don't need finally.

int retValue;

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


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;


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


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;


The following should work:

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;

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜