Removing excessive try-catch blocks

前端 未结 8 2390
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:36

    For cleanup rather use try-finally or implement the IDisposable as suggested by Amittai. For methods that return bool on error rather try and return false if the condition is not met. Example.

    bool ReturnFalseExample() {
        try {
            if (1 == 2) thow new InvalidArgumentException("1");
        }catch(Exception e) {
           //Log exception  
           return false;
        }
    

    Rather change to this.

    bool ReturnFalseExample() {
        if (1 == 2) {
           //Log 1 != 2
           return false;
        }
    

    If i'm not mistaken try catches are an expensive process and when possible you should try determine if condition is not met rather then just catching exceptions. }

提交回复
热议问题