Empty catch blocks

后端 未结 5 2045
春和景丽
春和景丽 2020-12-08 19:57

I sometimes run into situations where I need to catch an exception if it\'s ever thrown but never do anything with it. In other words, an exception could occur but it doesn\

5条回答
  •  庸人自扰
    2020-12-08 20:15

    Many of the other answers give good reasons when it would be ok to catch the exception, however many classes support ways of not throwing the Exception at all.

    Often these methods will have the prefix Try in front of them. Instead of throwing a exception the function returns a Boolean indicating if the task succeeded.

    A good example of this is Parse vs TryParse

    string s = "Potato";
    int i;
    if(int.TryParse(s, out i))
    {
        //This code is only executed if "s" was parsed succesfully.
        aCollectionOfInts.Add(i);
    }
    

    If you try the above function in a loop and compare it with its Parse + Catch equilvilant the TryParse method will be much faster.

提交回复
热议问题