c#错误“并非所有代码路径都返回值”
本文关键字:路径 代码 返回值 错误 | 更新日期: 2023-09-27 17:50:47
我把这部分代码从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();
}
}
如果代码抛出异常,则缺少返回值。
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;
}
如果try
块在return
语句之前发生异常,则catch
被执行并且不返回任何东西,因为您没有告诉它。
你可以这样做:
- 从
catch
块返回一个值。只有当它有意义并且你有一个可以返回的合理值时才这样做。请注意,返回null
通常是bug的来源,有一些模式可以避免这种情况。 - 重新抛出发生的异常,如果此时无法对此做任何处理(并返回一个有意义的对象)。你可以添加一行:
throw;
- 抛出一个不同的错误——你可以在一个新的异常中打包原始的异常,如果需要的话,提供关于上下文的额外细节。
您需要在catch子句之后添加一个返回语句!
如果在try catch子句中出现异常,则不会返回值。这就是你的错误所显示的
这是函数中常见的错误消息,因为函数被设计为返回一些值。如果你的代码传递了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(如果你没有返回什么)
- 在结束函数前给出带有变量名的返回关键字
这是因为在发生任何异常的情况下,异常将被抛出到catch,在这种情况下代码将不返回任何值。所以你必须从catch返回一些值来避免这个问题
将catch替换为:
catch
{
//error handling goes here
UnhandledExceptionHandler();
return new DataSet();
}
在任何情况下都必须返回正确的值。因此,如果在try/catch块中没有返回值,请尝试在try/catch块之外维护带有返回值的try/catch块。