MSVS C# fastest way to remove try-catch blocks?
I took over an incomplete project and to my utter disbelieve, every single function is wrapped with try-catch 开发者_开发百科statements in this same format:
try
{
// work work.
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, ...);
}
As I search SO for a method to quickly remove all these try-catch blocks, I find that people are actually looking for method to automatically wrap their functions with try-catch! hmmm... Is that good programming practice at all? Is there is method to remove all blocks instead so that it makes debugging easier and allows me to really solve the exceptions?
You can change the option here:
Debug -> Exceptions -> CLR Exceptions -> Check the "Thrown" checkbox.
This causes the compiler to break whenever an exception is thrown, before checking any catch
blocks.
This is a horrible programming practice. I once saw this as a bug mess up someone's database.
It is my firm opinion you are better off letting your program die a fiery death than mindlessly continue on in an unknown state.
I would do a find and replace on MessageBox.Show(ex
with throw //MessageBox.Show(ex
and replace them all. You will have to manually find the ones that should really be there and put them back.
Visual Studio's Regex search is pretty powerful, however it is a bit tricky to use, here is something that you might find useful in searching for your above code: (Note in the find dialog box, in the Options section choose "Use: Regular Expressions")
Will find your bad catches:
catch.*\n+:b+{[.:b\n]MessageBox.[.:b\n]*}
If you want to do a straight replace with a throw:
catch\n{\nthrow;\n}
I've discovered a solution to this for VB.NET.
Replace this:
\s(?<!End )Try((.|\r\n)+?)Catch(.|\r\n)+?(Finally((.|\r\n)+?)End Try|End Try)
...with this:
$1$5
It will remove the entire try/catch block while leaving behind only what was in the try and finally blocks. It doesn't work with nested try/catches, though, so you'd need to replace the nested blocks first and then the outer blocks last.
Quick and dirty trick:
- search & replace try -> if(true) //WAS TRY
- search & replace catch§ -> if(true) //WAS CATCH §
§ is a placeholder for the regex to match what is catched and put it after the comment WAS CATCH
by this way you can:
- revert searching WAS TRY and WAS CATCH §
- decide what has to be replaced and what has not when during rhe search
I use to comment with // DUMMY every catch that is temporary during the debug session.
(since this is a very old post, I didn't take all the time needed to write the regex etc... please be patient)
精彩评论