2022-01-27

try-catch instead of if in edge cases

Would it be a good idea to replace the if statements with try-catch in the following usecases (performance and readability wise?):

Example 1

public static void AddInitializable(GameObject initializable)
{
    if(!HasInstance)
    { // this should only happen if I have forgotten to instantiate the GameManager manually
        Debug.LogWarning("GameManager not found.");
        return;
    }

    instance.initializables.Add(initializable);
    initializable.SetActive(false);
}

public static void AddInitializable2(GameObject initializable)
{
    try
    {
        instance.initializables.Add(initializable);
        initializable.SetActive(false);
    }
    catch
    {
        Debug.LogWarning("GameManager not found.");
    }
}

Example 2

public static void Init(int v)
{
    if(!HasInstance)
    {// this should happen only once
        instance = this;
    }

    instance.alj = v;
}

public static void Init2(int v)
{
    try
    {
        instance.alj = v;
    }
    catch
    {
        instance = this;
        Init(v);
    }
}

Edit:

Question 2: How many Exceptions can I get to be still performance positive?



from Recent Questions - Stack Overflow https://ift.tt/3r3GiY8
https://ift.tt/eA8V8J

No comments:

Post a Comment