首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重构代码以排除尝试捕捉场景,最佳实践?

重构代码以排除尝试捕捉场景,最佳实践?
EN

Stack Overflow用户
提问于 2015-08-25 11:44:17
回答 1查看 936关注 0票数 1

由于Unity3D是如何通过WebGL在浏览器中工作的,尝试/捕捉的捕捉部分会立即使游戏崩溃。这主要是因为发布版本不支持它。(可以使用try/catch使用调试构建,但这也会带来后果)最后,我必须重构一些代码才能工作,而不需要在代码中使用try/catch,以防止它为用户锁定。

以下是我目前的情况:

代码语言:javascript
复制
try{
        using (StreamReader reader = new StreamReader(Application.persistentDataPath+"/"+"CHARVER.BIN"))
        {
            JSONNode characterImages;
            string json = reader.ReadToEnd();
            if(string.IsNullOrEmpty(json)){
                throw new System.IO.FileNotFoundException();
            }else{  
                characterImages = JSON.Parse(json);
                //test the image file inside
                Texture2D loadedImage = new Texture2D(1,1,TextureFormat.ARGB32,false);
                try{
                    loadedImage.LoadImage(File.ReadAllBytes(Application.persistentDataPath + characterImages ["Characters"][0]["texture"]));
                    if(!loadedImage){
                        throw new System.IO.FileNotFoundException();
                    }
                }
                catch(System.Exception ex){
                    Debug.LogError("[DOWNLOAD]Test image file was not found: "+ex);
                    ThrowBackToLogin("No image file was found.");
                    yield break;
                }
            }
        }
    }catch(System.Exception ex){
        Debug.Log("[DOWNLOAD]Test file was not found: "+ex);
        ThrowBackToLogin("No version file found.");
        yield break;
    }

我如何重构这个以删除尝试-捕捉部分?我不可能手动避免File.RealAllBytes向我抛出的所有异常,对吗?我可以想象,只调用一个"exception message“方法,只需要接收一条消息,并响应失败的检查和”返回“;就在此之后,(替换抛出的新System.IO.FileNotFoundException();),因为我自己抛出了该消息。但是,对于我无法控制的更先进的方法,它是如何工作的呢?

提前感谢-Smiley

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-25 13:21:15

好吧这个怎么样?

代码语言:javascript
复制
using (StreamReader reader = new StreamReader(Application.persistentDataPath+"/"+"CHARVER.BIN"))
{
    JSONNode characterImages;
    string json = reader.ReadToEnd();

    if(!string.IsNullOrEmpty(json))
    {
        characterImages = JSON.Parse(json);
        //test the image file inside
        Texture2D loadedImage = new Texture2D(1,1,TextureFormat.ARGB32,false);

        if(characterImages.Keys.Contains("Characters")
            && characterImages["Characters"].Count() > 0
            && characterImages["Characters"][0].Keys.Contains("texture"))
        {
            if(loadedImage.LoadImage(File.ReadAllBytes(Application.persistentDataPath + characterImages["Characters"][0]["texture"])))
                return;
        }
    }
    ThrowBackToLogin("No image file was found.");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32203101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档