techmanbd Posted January 31, 2008 Posted January 31, 2008 (edited) 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. 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# 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 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; Edited January 31, 2008 by techmanbd Quote Live as if you were to die tomorrow. Learn as if you were to live forever. Gandhi
Administrators PlausiblyDamp Posted January 31, 2008 Administrators Posted January 31, 2008 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
techmanbd Posted January 31, 2008 Author Posted January 31, 2008 I am running 2003. Quote Live as if you were to die tomorrow. Learn as if you were to live forever. Gandhi
techmanbd Posted February 1, 2008 Author Posted February 1, 2008 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. public string readGPIB(Device devGeneric) { string readIt; try { readIt = devGeneric.ReadString(); } catch { readIt = "NAN"; } return readIt; } Quote Live as if you were to die tomorrow. Learn as if you were to live forever. Gandhi
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.