在尝试捕获中使用泛型返回值

问题描述

我在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 @R_574_4045@ion about it.
        Debug.Log(e.ToString());
        return ?????;
    }
}

解决方法

这实际上取决于您要定义的应用程序行为。您可以让它返回new T() / default(我不建议这样做,因为用户无法告诉操作是否成功),也可以将异常向上抛出,以便可以处理其他地方。尝试捕获的全部要点是处理意外的特定行为,因此,除非您具有通用的处理方式,否则捕获通用异常不是一个好主意。

,

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

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

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<T>方法中我们不知道上下文,这就是为什么我们无法确定1..7中的哪个选项是最好的