【问题标题】:How can I check a file for an IndexOutOfRangeException and log it?如何检查文件中的 IndexOutOfRangeException 并记录它?
【发布时间】:2026-02-15 11:20:04
【问题描述】:

更新

try
        {
            //Attemps string conversion for each of the point's variables
            int.TryParse(row[0], out q.pointID); //Checks for existence of data on the line...
            float.TryParse(row[1], out q.xValue); //Input x-value
            float.TryParse(row[2], out q.yValue); //Input y-value
            float.TryParse(row[3], out q.zValue); //Input z-value
            float.TryParse(row[4], out q.tempValue); //Input temp-value
        }
        catch (IndexOutOfRangeException)
        {
            Debug.Log("File out of range...");
            errorLogScript.errorCode = 1100;
            SceneManager.LoadScene(4);
        }

这是我拥有的当前代码,但每当我尝试将场景转移到 errorScreen 时,它似乎就冻结了。话虽如此,我没有收到错误,但每当我尝试测试此错误时,我的代码都会冻结并且 Unity 会崩溃。

有人对我如何解决这个问题有任何想法吗?

OP

我目前正在使用 Unity 开发一个应用程序,我想创建一个错误/崩溃报告系统,在加载失败时向用户显示唯一的错误代码。由于这个特定的应用程序将被许多具有许多不同技能的人使用,我想在今年晚些时候发布它之前尽可能地打破它。在此过程中,我想提供一个快速参考,以便用户可以在文档中查找。

以下代码演示了如果用户输入的文件路径不存在会发生什么...

if (File.Exists(dropDownMenuScript.dataFileName + ".csv"))
    {
        Debug.Log("File found, loading..."); //Debugs success to console
    }
    else
    {
        Debug.Log("File not found, aborting..."); //Debugs the problem to console
        errorLogScript.errorCode = 1000; //Shows the code "E1000"
        SceneManager.LoadScene(4); //Loads the error-screen which displays the code
    }

我最近发现了另一个错误: “IndexOutOfRangeException”——在这种情况下,这与文件的解析有关,这意味着它存在但不符合与程序兼容的数据格式。我想为这个问题创建另一个错误日志,但我知道如何做到这一点,因为它是一个 Unity 编辑器错误。

如果这不是很清楚,我深表歉意,但如果您需要,我会提供所需的任何上下文。谢谢!

【问题讨论】:

  • 使用try catch处理异常
  • 你不能使用 try-catch 块并专门捕获 IndexOutOfRangeException 吗?

标签: c# unity3d debugging error-handling


【解决方案1】:

您不能使用 try-catch 块并专门针对 IndexOutOfRangeException 进行陷阱吗?

try
{
    //Your code...
}
catch(IndexOutOfRangeException iore)
{
    //Log here
}

【讨论】: