C#错误“并非所有代码路径都返回值” [英] C# error "Not all code paths return a value"

查看:92
本文介绍了C#错误“并非所有代码路径都返回值”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将这部分代码从vb转换为c#,并给出了此错误消息。 并非所有代码路径都返回值。问题是什么?

I translated this part of the code from vb to c# and giving me this error message. "Not all code paths return a value". What is the problem? Thanks in advance.

    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();
        }
    }


推荐答案

如果 try 语句中的 return catch 被执行并且不会返回任何内容,因为您没有告诉它。

If an exception occurs in your try block before the return statement, the catch is executed and that does not return anything, because you did not tell it to.

您可以执行以下操作之一:

You can do one of these:


  • catch 块返回一个值。仅在有道理并且您具有可以返回的明智价值时才这样做。请注意,返回 null 是错误的常见来源,并且有模式可以避免这种情况。

  • 重新抛出发生的异常,如果此时您无法执行任何操作(并返回一个感)。您可以通过添加以下行来做到这一点: throw;

  • 抛出其他错误-您可以将原始异常打包到新的,提供有关上下文的更多详细信息。

  • Return a value from the catch block. Do this only if it makes sense and you have a sensible value you can return. Be aware that returning null is a usual source of bugs and there are patterns out there to avoid just that.
  • Re-throw the exception that occurred, if you cannot do anything at this point about it (and return an object that makes sense). You can do this by adding a line that says: throw;
  • Throw a different error - You can package the original exception in a new one, providing extra details about the context, if necessary.

这篇关于C#错误“并非所有代码路径都返回值”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆