【问题标题】:return value in Try Catch with genericsTry Catch 中的返回值与泛型
【发布时间】:2020-08-14 15:14:59
【问题描述】:

我在try/catch 块中指定正确的返回值时遇到问题。 我是新手级别的脚本编写者,以前从未使用过泛型。

错误信息是:

“需要一个可转换为T 的对象”

我需要在try/catch 末尾返回什么具体内容?

private static T LoadData<T>(string filePath)
{
    try
    {
        return JsonUtility.FromJson<T>(File.ReadAllText(filePath));
    }
    catch(Exception e)
    {
        // Something went wrong, so lets get information about it.
        Debug.Log(e.ToString());
        return ?????;
    }
}

【问题讨论】:

  • 唯一明智的做法是重新抛出异常。或者return default;我推荐前者。
  • 我建议重新抛出异常:throw; 而不是任何类型的return

标签: c# generics try-catch


【解决方案1】:

这实际上取决于您要定义的应用程序行为。你可以让它返回一个new T()/default(我不建议这样做,因为用户无法判断操作是否成功)或者你可以将异常提高一个级别,以便可以在其他地方处理它。 try catch 的全部意义在于处理意外的特定行为,因此除非您有通用的处理方式,否则捕获通用异常并不是一个好主意。

【讨论】:

  • 请注意,要返回 new T(),您必须约束 T 以拥有无参数构造函数 (where T:new())
  • @DStanley 抱歉,我的意思不是 new T(),在我的脑海中,我曾设想使用 Activator 来实例化对象,但是是的,你是对的。
  • 这两个选项的代码示例会很有用。
【解决方案2】:

某事出错时,我们不能只是忽略它;如果我们没有足够的信息来做出决定,最好的选择是升级问题:可能是顶级方法知道该做什么。

所以我建议重新抛出异常而不是返回任何值:

private static T LoadData<T>(string filePath)
{
    try
    {
        return JsonUtility.FromJson<T>(File.ReadAllText(filePath));
    }
    catch(Exception e)
    {
        // Something went wrong, so lets get information about it.
        Debug.Log(e.ToString());
        
        // let top level method decide what to do:
        //   1. Do nothing (just ignore the exception)
        //   2. Do something (e.g. change permission) with filePath
        //   3. Try load from some other file
        //   4. Try load from some other source, say RDBMS
        //   5. Use some default value
        //   6. Close the application
        //   7. ....    
        throw;
    }
}

请注意,在这里,在 LoadData&lt;T&gt; 方法中,我们不知道上下文,这就是为什么我们无法确定 1..7 中的哪个选项是最佳选项

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2018-05-23
    • 2010-10-10
    • 2012-04-24
    • 2018-11-05
    • 2014-12-26
    相关资源
    最近更新 更多