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
Here is a regular expression that finds also catch blocks with only comments inside :
catch:b*\([^)]*\)[:b\n]*\{([:b\n]|(\/\*[^*]*\*\/)|(//[^\n]*))*\}
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}
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*\}
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
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.
Use use the global find dialog, turn on regular expressions and then search for:
catch:b*\([^)]*\):b*\{:b*\}