C#错误“并非所有代码路径都返回值”

编程入门 行业动态 更新时间:2024-10-27 04:34:07
本文介绍了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

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#错误“并非所有代码路径都返回值”

本文发布于:2023-11-10 01:20:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   返回值   错误   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!