Why was try...catch was recommended to me here?

43 Views Asked by At

I'm modding a game which uses JavaScript for its UI. All its scenes look something like the following:

var model;
var handlers = {};

$(document).ready(function()
{
    // code
    loadSceneMods('scene_name')
    // more code
});

The function called does the following:

function loadSceneMods(scene) {
    
    if (_.has(scene_mod_list, scene)){
        debuglog("loadSceneMods for scene:" + scene) // outputs to console
        loadMods(scene_mod_list[scene]);
    }else{
        debuglog("loadSceneMods no mods for scene: " + scene) // outputs to console
    }
}

function loadMods(list) {
    var start = Date.now();
    var i;
    var mod;
    var type;

    var js = /[.]js$/;
    var css = /[.]css$/;

    if (api.Panel.pageName === 'game')
        init_browser();

    console.log("loadMods...");
    for ( i = 0; i < list.length; i++) {
        mod = list[i];

        console.log(encode(mod));

        if (mod.match(js))
            loadScript(mod);

        if (mod.match(css))
            loadCSS(mod);
    }
    console.log("loadMods done. mods loaded in " + (Date.now() - start)/1000 + " seconds" );
}

When I was learning JavaScript I was told by someone who is a programmer by day how I should be structuring my code as best practice. However, I have since lost contact and never asked why this structure is what they said I should use:

var modSceneNameLoaded;

if (!modSceneNameLoaded) {
  modSceneNameLoaded = true;

  function modSceneName() {
    try {
      // code
    } catch (e) {
      console.error(e);
      console.error(JSON.stringify(e));
    }
  }
  modSceneName();
}

My understanding of this block is that it achieves the following:

  1. It will prevent the code being loaded more than once by the game. This seems like sound defensive code, if perhaps a bit excessive.
  2. It contains all the mod's logic in its own function to avoid variable clashes and polluting the global namespace. This appears essential.
  3. That it will catch any errors. I don't really understand if this is necessary, or how it differs from normal error output in its current form, even after reading up on try...catch. The only bit I get is that JSON.stringify(e) allows me to see the full output of an error.

As my code has grown the nesting this introduces is more of an issue. However, I'm struggling to make sound decisions around what trade-offs are acceptable without first fully understanding why they advised this structure.

My questions are:

  1. Are my understandings 1 & 2 correct?
  2. Is a try...catch really necessary or adding value here?
0

There are 0 best solutions below