techmanbd
Junior Contributor
I am in the process of learning the C# ways, and I came across this. In VB I can do this. For the record why I use the TRY Catch is that if a device shuts down on the GPIB bus then it raises an exception and I don't want to the program to crash.
so here is how I converted in C#
I tried the return in the TRY and CATCH area and I get the error
"Not all codes return a value"
so I figured I can put it in finally. Basically I will make a bool variable before the try and then get to finally and return it there. But then I get this error:
"Control cannot leave the body of a finally clause"
So if I put the return below like so, I get no error
What I am afraid of here if there is an exception, it won't make it to the return. Unless in C# this does, because in VB when it goes to the catch exception portion, it exits the sub.
Or would I just need to do?
Finally{}
Return boolYes;
Visual Basic:
Public Function GPIBWrite(ByVal devGeneric As Device, ByVal strCommand As String) As Boolean
Try
devGeneric.Write(strCommand)
Return True
Catch ex As Exception
Return False
End Try
End Function
so here is how I converted in C#
C#:
public bool writeGPIB(Device devGeneric, string strCommand)
{
try
{
devGeneric.Write(strCommand);
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
finally
{
// return true;
}
}
I tried the return in the TRY and CATCH area and I get the error
"Not all codes return a value"
so I figured I can put it in finally. Basically I will make a bool variable before the try and then get to finally and return it there. But then I get this error:
"Control cannot leave the body of a finally clause"
So if I put the return below like so, I get no error
C#:
public bool writeGPIB(Device devGeneric, string strCommand)
{
bool boolYes;
try
{
devGeneric.Write(strCommand);
boolYes = true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
boolYes = false;
}
return boolYes;
}
What I am afraid of here if there is an exception, it won't make it to the return. Unless in C# this does, because in VB when it goes to the catch exception portion, it exits the sub.
Or would I just need to do?
Finally{}
Return boolYes;
Last edited: