第一回认识try catch

来源:互联网 发布:linux搭建php运行环境 编辑:程序博客网 时间:2024/06/05 00:43

在bowling游戏里,由于ScoreDisplay中arraylist out of range的错误,使得HandleBowl执行失败,又使得CheckResult执行失败因为CheckResult使用了HandleBowl,最后每个Update都失败因为CheckResult每帧都被call,错误原始结果像这样:


ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[System.Int32].CheckIndex (Int32 index) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:419)
System.Collections.Generic.List`1[System.Int32].set_Item (Int32 index, Int32 value) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:637)
ScoreDisplay.FillRollCard (System.Collections.Generic.List`1 rolls) (at Assets/Script/ScoreDisplay.cs:24)
GameManager.HandleBowl (Int32 pins) (at Assets/Script/GameManager.cs:37)
LaneCheckBox.CheckAndManagerResult () (at Assets/Script/LaneCheckBox.cs:81)
LaneCheckBox.Update () (at Assets/Script/LaneCheckBox.cs:37)


在错误处使用了try catch后的好处:

* try{可能错误语句}catch{ Debug.LogWarning("错误在xxx这个位置!") }

这样运行后出现错误的时候,以上的原始错误信息就变成了一个warning : 错误在xxx这个位置! 这样就定位了错误


* 原始错误是Log error,错误语句下面的语句就不会执行,游戏就不能继续运行,但是如果catch以后改为log warning,错误语句下面的东西还会执行,这样虽然某处有错误,但整个游戏还是能继续下去


同时使用try catch要注意的点:

你必须清楚错误是什么,再从catch中log warning,因为游戏会继续下去。如果你不知道错误到底是什么也就不知道他能引起什么样的问题,但是如果你知道问题是什么,比如在bowling中问题是获得的分数不会显示,或在别的游戏中你知道会引起的问题很微小,那么就可以使用catch log warning,避免小错误crash整个游戏。

0 0
原创粉丝点击