A macro to protect a code section with a Try…Catch block

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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.