Search code examples
c#xnaloadingtexture2d

Loading Texture2D Inconsistently Fails


Sometimes (not always, most times it works flawlessly), I catch the exception I provided when it fails to load a Texture2D.

public static class Extras
{
    public static class Load
    {
        private static Dictionary<string, Texture2D> Textures;

        public static Texture2D Texture(string Path)
        {
            if (Textures == null) Textures = new Dictionary<string, Texture2D>();
            if (Textures.ContainsKey(Path)) return Textures[Path];
            else
            {
                try { Textures.Add(Path, Service<ContentManager>().Load<Texture2D>(Path)); return Textures[Path];
                catch { throw new ArgumentNullException(string.Format("Failed to load Texture2D from \"{0}\"!", Path)); }
            }
            return null;
        }
    }

    public static class Services
    {
        private static GameServiceContainer Container;

        public static T Get<T>() { return (T)Container.GetService(typeof(T)); }
        public static void Add<T>(T Service) { if (Container == null) Container = new GameServiceContainer(); Container.AddService(typeof(T), Service); }
        public static void Remove<T>() { Container.RemoveService(typeof(T)); }
    }
    public static T Service<T>() { return Services.Get<T>(); }
}

-

When the game loads:

Extras.Services.Add<ContentManager>(Content);

Texture2D Texture = Extras.Load.Texture("Textures\\Player");

Now most times it works, but sometimes I get the exception (when first loading the texture into the game).

Why does it inconsistently fail to load the Texture2D?


Solution

  • Firstly, format your code, especially if you are going to post it.

    try
    {
        Textures.Add(Path, Service<ContentManager>().Load<Texture2D>(Path));
        return Textures[Path];
    }
    catch
    {
        throw new ArgumentNullException(string.Format("Failed to load Texture2D from \"{0}\"!", Path));
    }
    

    Or just press Ctrl+E, Ctrl+D (in my VS 2010 by default) before copy code snippet.

    Secondly, section catch should process already trown exception, but you ignore it just throw new one instead. Also notice that ArgumentNullException is a special subclass of Exception which occurs when there is an attempt to access a non-existent object. If you want throw custom exeption it should logically correspond to the situation. If you are not 100% sure that what happened, throw basic Exception object.

    try
    {
        // critical code section
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
    

    Please read the documentation about try-catch to understand how it works.

    And last. In Visual Studio (my is 2010) you can go to the Debug -> Exceptions item and check first "CLR Exceptions" checkbox. It allows you see runtime exceptions immediately once they are thrown.