C#错误“并非所有代码路径都返回值”
我将这部分代码从vb翻译成了c#并给了我这个错误信息。 “并非所有代码路径都返回值”。 问题是什么? 提前致谢。
public DataSet LoadSearchDataSet(string strConnection, string strSQL) { //The purpose of this function is to create and populate a data //set based on a SQL statement passed in to the function. try { DataSet dsData = new DataSet(); //call the table in the local dataset "results" since the values //may be coming from multiple tables. string strTableName = "Results"; bool blnRunStoredProc = false; dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData); WriteSampleDataToOutputWindow(dsData); //return the data set to the calling procedure return dsData; } catch { //error handling goes here UnhandledExceptionHandler(); } }
如果在return
语句之前在try
块中发生exception,则执行catch
并且不返回任何内容,因为您没有告诉它。
你可以做其中一个:
- 从
catch
块返回一个值。 只有在它有意义并且你有一个合理的价值可以返回时才这样做。 请注意,返回null
是错误的常见来源,并且有一些模式可以避免这种情况。 - 重新抛出发生的exception,如果此时无法做任何事情(并返回一个有意义的对象)。 您可以通过添加以下行来执行此操作:
throw;
- 抛出不同的错误 – 您可以将原始exception打包到新的exception中,如有必要,提供有关上下文的额外详细信息。
在代码抛出exception的情况下,您缺少返回值。
public DataSet LoadSearchDataSet(string strConnection, string strSQL) { //The purpose of this function is to create and populate a data //set based on a SQL statement passed in to the function. DataSet dsData = new DataSet(); try { //call the table in the local dataset "results" since the values //may be coming from multiple tables. string strTableName = "Results"; bool blnRunStoredProc = false; dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData); WriteSampleDataToOutputWindow(dsData); } catch { //error handling goes here UnhandledExceptionHandler(); } //return the data set to the calling procedure return dsData; }
你需要在catch子句后添加一个return语句!
如果try catch子句中存在exception,则不会返回值。 这正是你的错误所表明的。
这是函数中的常见错误消息,因为函数旨在返回一些值。 如果你的代码通过catch部分,它将到达函数的末尾而不返回任何东西,那就是你需要返回值的地方。
像这样重写:
DataSet dsData = null; try { //call the table in the local dataset "results" since the values //may be coming from multiple tables. string strTableName = "Results"; bool blnRunStoredProc = false; dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData); WriteSampleDataToOutputWindow(dsData); } catch { //error handling goes here UnhandledExceptionHandler(); } //return the data set to the calling procedure return dsData;
您可以通过以下方式解决此问题
- 将函数返回更改为VOID(如果没有返回某些内容)
- 在结束函数之前给出带变量名的return关键字
这是因为在发生任何exception的情况下,exception将抛出到catch,在这种情况下代码不会返回任何值。 所以你必须从catch中返回一些值来避免这个问题
用这个替换捕获:
catch { //error handling goes here UnhandledExceptionHandler(); return new DataSet(); }
在任何情况下都必须返回适当的值。 因此,如果在try / catch块中没有返回任何内容,请尝试使用返回值或try / catch块外部维护try catch块。