When you’re working with the Visual Studio .NET code editor, typing a Try keyword plus the Enter key automatically creates the End Try statement. The following simple macro does something more interesting: it lets you select a portion of code and protect it with a Try…Catch…Finally…End Try block with a single key. Here’s the macro source code:
Sub CreateTryCatchFinally() DTE.ActiveDocument.Selection.Cut() DTE.ActiveDocument.Selection.Indent(2) DTE.ActiveDocument.Selection.Text = "Try" DTE.ActiveDocument.Selection.NewLine() DTE.ActiveDocument.Selection.Paste() DTE.ActiveDocument.Selection.NewLine() DTE.ActiveDocument.Selection.DeleteLeft() DTE.ActiveDocument.Selection.Text = "Catch ex as Exception" DTE.ActiveDocument.Selection.NewLine() DTE.ActiveDocument.Selection.DeleteLeft() DTE.ActiveDocument.Selection.NewLine() DTE.ActiveDocument.Selection.DeleteLeft() DTE.ActiveDocument.Selection.Text = "Finally" DTE.ActiveDocument.Selection.NewLine()End Sub
You should press Alt-F11 to bring up the macro IDE, and paste this code in an appropriate macro module. Then you should display the Tools-Options dialog and assign this macro a keyboard shortcut, for example the following (two keystrokes): Ctrl-Shift-V, Ctrl-Shift-T.
After you’ve done this, you can just select a block of code that you want to protect from exception and press the shortcut key, and see the Try block being created before your eyes. Note that you might need to reformat the code to achive the best indentation. If automatic indentation is on, you can do this by simply selecting the statements between Try and End Try keywords and press the Tab key once.