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 find all empty try catch blocks in a solution?
使用全局查找对话框,打开正则表达式,然后搜索:
catch:b*\([^)]*\):b*\{:b*\}
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}
FxCop会发现它们以及许多其他潜在问题。
Do you have ReSharper ? This should hilight the issues found in code.
这是一个正则表达式,它也可以找到仅包含注释的catch块:
catch:b*\([^)]*\)[:b\n]*\{([:b\n]|(\/\*[^*]*\*\/)|(//[^\n]*))*\}
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*\}
Press Ctrl + Shift + F. Expand Find options. Check Use Regular Expressions Paste this regex.
catch\s*(\(\s*Exception(\s*\w+)?\))?\s*\{\s*\}
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.
catch\s*((?.+Exception(\s*\w+)?))?\s*{\s*([:b\n]|(/*[^ ] */)|(//[^\n] )) }
Visual Studio 2022. Only This expression is actually working.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.