Removing excessive try-catch blocks

前端 未结 8 2410
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:38

    we can remove try and catch by adding condition Like

     string emailAddresses = @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$";
            if (!Regex.IsMatch(Email, emailAddresses))
            {
                throw new UserFriendlyException($"E-mail Address Is not Valid");
            }**strong text**
    
    0 讨论(0)
  • 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) {}
    
    0 讨论(0)
提交回复
热议问题