try catch and return value
-
I'm writing a function as below: public string returnString() { try { //open connections return var1; } catch (Exception ex) { //write to trace } finally { //close connections } } I'm getting an error that says the function will not return a value in some execution. Where should I return the value? After finally? X|
-
I'm writing a function as below: public string returnString() { try { //open connections return var1; } catch (Exception ex) { //write to trace } finally { //close connections } } I'm getting an error that says the function will not return a value in some execution. Where should I return the value? After finally? X|
If your
try
fails, it will jump to thecatch
block. There is noreturn
statement in thecatch
block therefore, once the error is handled it does not know what toreturn
out of the method. You either need an additional return in the catch block or you need to return something after the finally block.
My: Blog | Photos WDevs.com - Open Source Code Hosting, Blogs, FTP, Mail and More
-
If your
try
fails, it will jump to thecatch
block. There is noreturn
statement in thecatch
block therefore, once the error is handled it does not know what toreturn
out of the method. You either need an additional return in the catch block or you need to return something after the finally block.
My: Blog | Photos WDevs.com - Open Source Code Hosting, Blogs, FTP, Mail and More
For example, if I am retrieving data from a DB and returning the dataset. An exception occurs and no data is retrieved. In this case, should I still return the dataset in the catch block\after finally? My initial thought was that I wouldn't return anything if an exception occurs. :(
-
For example, if I am retrieving data from a DB and returning the dataset. An exception occurs and no data is retrieved. In this case, should I still return the dataset in the catch block\after finally? My initial thought was that I wouldn't return anything if an exception occurs. :(
You must
return
something as your method signature tells the caller that you will. If the thing fails and you have nothing thenreturn null;
My: Blog | Photos WDevs.com - Open Source Code Hosting, Blogs, FTP, Mail and More
-
You must
return
something as your method signature tells the caller that you will. If the thing fails and you have nothing thenreturn null;
My: Blog | Photos WDevs.com - Open Source Code Hosting, Blogs, FTP, Mail and More
I see! Thanks very much Colin! Regards, Os