C# Function Try-Catch Question

techmanbd

Junior Contributor
Joined
Sep 10, 2003
Messages
397
Location
Burbank, CA
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.

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:
You could just have a return after the try ... catch block and return true - that should work.

However I just tried a simply try .. catch block here that did pretty much nothing but return a true in the try blaock and false in the catch and didn't get an error. What version of VS are you using as I'm running 2008 here.
 
I have been testing my code. And putting the return after the Try Catch still works. At least for the 2003 version. They must have done some changes.

C#:
	public string readGPIB(Device devGeneric)
		{
			string readIt;
			try
			{
				readIt = devGeneric.ReadString();
			}
			catch
			{
				readIt = "NAN";
			}
			return readIt;
		}
 
Back
Top