Removing excessive try-catch blocks

前端 未结 8 2405
Happy的楠姐
Happy的楠姐 2021-02-14 19:10

I\'m refactoring a medium-sized WinForms application written by other developers and almost every method of every class is surrounded by a try-catch block. 99% of t

8条回答
  •  心在旅途
    2021-02-14 19:40

    As an option for "return-false-on-error" you can clean up the code this way:

        static class ErrorsHelper {
            public static bool ErrorToBool(Action action) {
                try {
                    action();
                    return true;
                } catch (Exception ex) {
                    LogException(ex);
    
                    return false;
                }
            }
    
            private static void LogException(Exception ex) {
                throw new NotImplementedException();
            }
        }
    

    and usage example:

        static void Main(string[] args) {
            if (!ErrorToBool(Method)) {
                Console.WriteLine("failed");
            } else if (!ErrorToBool(() => Method2(2))) {
                Console.WriteLine("failed");
            }
        }
    
        static void Method() {}
    
        static void Method2(int agr) {}
    

提交回复
热议问题