Click here to Skip to main content
13,142,065 members (51,573 online)
Click here to Skip to main content
Add your own
alternative version


24 bookmarked
Posted 8 Jul 2005

Adding Try/Catch Block using AddIn For Visual Studio .NET 2003

, 8 Jul 2005
Rate this:
Please Sign up or sign in to vote.
This add-in adds try/catch blocks inside your method automatically on clicking it.


This is an extensibility of VS.NET 2003.This add-in adds try/catch blocks inside your method. This will save development time. Basically it checks whether it is a method and also whether a try/catch block already exists. If not it adds a try/catch inside your method. Usually programmers forget to write try/catch during development time and at the slast minute they will add it in all the pages. That time this will be very useful .They can just execute this add-in which will automatically add try/catch blocks inside your method.

Installation Steps

  1. Run the Setup.exe from the
  2. Select the installation folder where you want to install the setup.
  3. Click Close to finish the installation.

Using the Tool

After you install the add-in, it will be listed in the Tools menu automatically. To use this you have to place your cursor inside the method and click this add-in. Adding to the ToolBar: to add it to your toolbar, go to Tools -> Customize -> Select Command tab, then choose AddIn and drag AddTryCatch to the toolbar and drop it.

Source Code Overview

You have to declare this struct which contains the caret position, function name, start and end position of the function.

private struct SFunction
    public string FuncName;
    public int StPtr;
    public int EndPt;
    public int CaretPos;
    public bool SearchDone;
private SFunction OneFunction;

This method checks for the active document and calls GetWholeProcedure() to add the try/catch block. Add AddingTryCatch() method call in the Exec method (e.g.) handler = AddingTryCatch();

public bool AddingTryCatch()
    if (applicationObject.ActiveDocument !=null)
    return true;

Code listed below checks for the function in the current window and fetches the function where the cursor is placed. Then it checks if try/catch block exists already. Then it inserts a try at the start of the function and catch/finally at the end of the function.

public void GetWholeProcedure()
    TextSelection ts = (TextSelection) applicationObject.ActiveDocument.Selection;
    EditPoint ep = ts.ActivePoint.CreateEditPoint();
    OneFunction.SearchDone= false;

    // if we found the function, get the code
    if (OneFunction.SearchDone)
        string s = ep.GetLines(ep.Line,OneFunction.EndPt+1);
        // Check for Try/Catch Exists
        int found = s.IndexOf("try"); 
        int foundcatch = s.IndexOf("catch("); 
        int position = 2;
        // If not Try/Catch Exists
        if(found == -1 || foundcatch == -1 )
            TextSelection ts1 = 
            // Sets the Insertion point based on webservice or webform file
                      != -1 && s.IndexOf("[WebMethod]") != -1 )  
                position = 3;
                position = 2;
            ts1.GotoLine((OneFunction.StPtr + position),true);
            // Inserts Try at start of the function
            EditPoint e =ts1.TopPoint.CreateEditPoint();
            // Indents the lines 
            int currentposition = OneFunction.StPtr + position + 1 ;
            for(int intLoop = 1 ; intLoop <=(OneFunction.EndPt - 
                ts1.GotoLine((currentposition + intLoop),true);
                if(ts1.Text.Equals("") != true )
            // Goes to the end of the function and inserts Catch/Finally Block.
            e.Insert("\t\t\t}\n\t\t\tcatch(Exception ex)\n\" + 
                     "t\t\t{\n\t\t\t\tthrow ex;\n\t\t\t}\n\" + 
            System.Windows.Forms.MessageBox.Show("Try/Catch Block already exists"); 

The below functions are the major things which find out the function in the active window. It checks for the function in the caret position and returns the starting and ending point of the function and sets the searchDone flag to true. Some of the extensibility classes used are:

  • ProjectItem - Represents an item in a project.
  • FileCodeModel - Allows access to programmatic constructs in a source file.
  • CodeElements - Represents a code element or construct in a source file.
  • CodeNamespace - Represents a namespace construct in a source file.
  • CodeClass - Represents a class in source code.
// enumerates all classes in all namespaces in a window 
private void SearchForFunctionInCurrentWindow()
    ProjectItem pi = (ProjectItem) applicationObject.ActiveWindow.ProjectItem;
    FileCodeModel fcm = pi.FileCodeModel;

    if ( fcm!=null) 
private void GetFunction(CodeElements elements)
    // Looks for the function and returns the code.
    CodeElements members;
    foreach (CodeElement elt in elements)
            return ;

        if (elt.Kind==vsCMElement.vsCMElementFunction )
            if(OneFunction.CaretPos>= OneFunction.StPtr && 
               OneFunction.CaretPos <= OneFunction.EndPt)
            members = GetMembers(elt);
            if (members != null )
private CodeElements GetMembers(CodeElement elt)
    CodeElements members = null ;
    if(elt!= null)
        switch ( elt.Kind)
            case (vsCMElement.vsCMElementNamespace ):
                CodeNamespace cdeNS = (CodeNamespace) elt;
                members = cdeNS.Members;
                break ;
            case (vsCMElement.vsCMElementClass):
                CodeClass cdeCL = (CodeClass) elt;
                members = cdeCL.Members;
            case (vsCMElement.vsCMElementFunction):
                // functions dont have members
    return members;


Hope this tool would be useful. Good day...


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

India India
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
itsho18-Jan-11 22:14
memberitsho18-Jan-11 22:14 
Question2005 Pin
Eric Fleet6-Sep-07 3:11
memberEric Fleet6-Sep-07 3:11 
GeneralGood tool for the .NET devs Pin
harikaran28-Jul-05 18:36
memberharikaran28-Jul-05 18:36 
GeneralNice Article Pin
Vasudevan Deepak Kumar27-Jul-05 22:39
memberVasudevan Deepak Kumar27-Jul-05 22:39 
GeneralIt is Nice Add-On utility Pin
sengu2van26-Jul-05 18:25
membersengu2van26-Jul-05 18:25 
GeneralException Handling Pin
Santosh Sinha24-Jul-05 18:59
memberSantosh Sinha24-Jul-05 18:59 
GeneralHi Pin
Santhi.M10-Jul-05 19:53
memberSanthi.M10-Jul-05 19:53 
GeneralCant download source. Pin
mellospank8-Jul-05 1:44
membermellospank8-Jul-05 1:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170915.1 | Last Updated 8 Jul 2005
Article Copyright 2005 by Santhi.M
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid