C#: Find all empty catch blocks

前端 未结 9 1290
逝去的感伤
逝去的感伤 2020-12-23 22:08

I am reviewing some code.

I have notice some empty catch blocks. Not a good idea since somethings do not work and you cannot see why.

Is there an easy way to

相关标签:
9条回答
  • 2020-12-23 22:44

    Here is a regular expression that finds also catch blocks with only comments inside :

    catch:b*\([^)]*\)[:b\n]*\{([:b\n]|(\/\*[^*]*\*\/)|(//[^\n]*))*\}
    
    0 讨论(0)
  • 2020-12-23 22:45

    Expanded the accepted answer to satisfy all the conditions described below. Updated for Visual Studio 2017/2019, works for both C# and C++.

    Use the find dialog (CTRL+SHIFT+F), turn on regular expressions and search for:

    ^(?!\/\/|\/\*).*catch\s*(?:\([^)]*\))*\s*\{\s*(?:(?:\/\/|\/\*).*(\*\/)?\s*)*\}
    

    Matches:

    catch {}
    catch{}
    catch{
    }
    catch 
    {}
    catch () {}
    catch (...) {}
    catch (int x) {}
    catch (Exception x) {}
    catch (Exception ex){
    }
    catch(...){
    }
    } catch (...){
    /**/
    }
    } catch (...){
    /**/
    ///
    }
    } catch (...){
    //
    //
    /**/
    }
    catch (...)
    {}
    catch(...) { //single line
    }
    catch(...) { 
    //single line}
    catch(...) { 
    //single line
    }
    catch(...) { /*multiline*/
    }
    catch(...) {
     /*multiline*/}
    catch(...) {
     /*multiline*/
    }
    catch (...){ // int i = 0; }
    

    Does not match:

    // catch () {}
    /* catch () {} */
    catch (...){ int i = 0;}
    catch (...){ 
    int i = 0;}
    catch (...){int i = 0;
    }
    catch (...){ 
    // Comment
    int i = 0;}
    catch (...){ int i = 0; // Comment}
    
    0 讨论(0)
  • 2020-12-23 22:46

    Thanks to Stefan for the Regex suggestion. I found that the suggested regex does not find catch blocks where the exception is not specified, ie:

    catch { }
    

    I tweaked Stefan's slightly to make the exception brace optional:

    catch:b*(\([^)]*\))*:b*\{:b*\}
    
    0 讨论(0)
  • 2020-12-23 22:52

    Expanding on @bobah75 's answer, it wouldn't recognize this line

    catch (System.Data.Entity.Core.EntityException ex)
    {
    }
    

    So to fix that, here is the solution

    catch\s*(\(?.+Exception(\s*\w+)?\))?\s*\{\s*([:b\n]|(\/\*[^*]*\*\/)|(//[^\n]*))*\}
    

    you can test it out here

    0 讨论(0)
  • 2020-12-23 22:54

    If you can, I would suggest using Sonar Analyzer. You can add it via NuGet manager in Visual Studio.

    It will show all unused catch blocks and also show you a tip what do do with it, something in lines of: "Implement or comment why empty."

    Also, it will show you a lot more of possible code issues.

    0 讨论(0)
  • 2020-12-23 22:59

    Use use the global find dialog, turn on regular expressions and then search for:

    catch:b*\([^)]*\):b*\{:b*\}
    
    0 讨论(0)
提交回复
热议问题