views:

248

answers:

5

Hey guys,

Anyone know if there is a keystroke shortcut or option to autogenerate a try/catch block around a statement in Visual Studio 2010? I can see what exceptions are thrown if I look at the overlay documentation when I hover over a statement. I'd like to right click -> generate try/catch, as it would save a lot of time in handling all possible cases.

Is this possible?

+4  A: 

Have you tried using snippets?

Lucas B
+14  A: 

Using the mouse

  1. Mark your code
  2. Right-click
  3. Select Surround with...
  4. Double-click try

Using the keyboard #1

  1. Mark your code using Shift, CTRL+A, or whatever works for you
  2. Press Menu key / Application key (alternatively Shift+F10)
  3. Type S
  4. Type T
  5. Press Enter or Tab

Using the keyboard #2 (as perlox and Fredrik Norlin points out)

  1. Mark your code using Shift, CTRL+A, or whatever works for you
  2. Press CTRL+K, followed by CTRL+S
  3. Type T
  4. Press Enter or Tab
sshow
Can it be done without removing one's fingers from the keyboard? That would save even *more* time!
FrustratedWithFormsDesigner
@FrustratedWithFormsDesigner If you have the context menu button on your keyboard it can be.
a_hardin
Surround with... default keyboard shortcut is Ctrl+K, Ctrl+S
Fredrik Norlin
+8  A: 

type try then hit Tab,Tab

2xTab activates a code snippet.

type tryf,Tab,Tab to activate the try..finally block instead

Peter Perháč
Is there any way to add try, catch, finally?
Meleak
well, sure :-) you could always a) download additional code snippets, b) write your own code snippets, it's easy!
Peter Perháč
+5  A: 

I was going to comment on sshow's post (since this doesn't require a whole "answer"), but I can't since I don't have enough points...if you don't want to remove your fingers from the keyboard, you can hit CTRL+K, CTRL+S, then T, then ENTER. That's basically what he said, but without using the mouse.

http://msdn.microsoft.com/en-us/library/6hf704tz%28VS.80%29.aspx

perlox
`+1` I didn't think of the actual keyboard shortcuts
sshow
+1  A: 

I use CodeRush from DevExpress. I can use the key strokes "TC" to generate. It works with C# too.

    Try

                Catch ex As Exception
                    dmPrgm_Err(Err, ex)
                End Try

I then can use TSC for a Try SQL Catch with custom message boxes.

            Try

                Catch ex As SqlException
                    dmSQLErr(ex)
                Catch ex As Exception
                    dmPrgm_Err(Err, ex)
                End Try
Jeff