Reputation: 21621
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
Upvotes: 0
Views: 468
Reputation: 9936
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;
}
}
Upvotes: 3
Reputation: 8425
You don't need finally
.
int retValue;
try
{
// do something
retValue = something;
return retValue;
}
catch (ApplicationException ex) // or just Exception
{
return 0;
}
Upvotes: 1
Reputation: 11397
public int returnValue()
{
int returnValue=0;
try
{
returnValue = yourOperationValue;
}
catch {}
finally
{
}
return returnValue;
}
Upvotes: 1
Reputation: 107247
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;
Upvotes: 1
Reputation: 6617
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;
Upvotes: 1
Reputation: 38825
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);
}
Upvotes: 1
Reputation: 43098
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;
Upvotes: 1