Solved

To have goto in Catch which return to Try block

Posted on 2009-07-07
7
455 Views
Last Modified: 2013-12-17


Hi experts!

  Im using C# 2008 , WinForm NET 2. I want to ask .. if is allowed to have Goto in Catch which return to Try block ?  Look example code for more, I put all my function , search for TryAgain


public static SqlDataReader GetReader(string SQL,g.ParamRead[] paramList,int iCount)

        {

           

            TryAgain:

			SqlCommand command = new SqlCommand(SQL, Cn);
 

            if (SQL.StartsWith("spL")) command.CommandType = CommandType.StoredProcedure;
 

            if (iCount>0)

            {

                for (int i=1;i<=iCount;i++)

                {

                    SqlParameter paramName = new SqlParameter(paramList[i].Name, paramList[i].Type);

                    paramName.Value = paramList[i].Value;

                    paramName.Direction = ParameterDirection.Input;

                    command.Parameters.Add(paramName);

                }

            }
 

            try

            {

           //     command.CommandTimeout = g.CONNECT_TIMEOUT_FORCOMMAND;

                SqlDataReader DR = command.ExecuteReader();

                return DR;

            }

            catch (SqlException ex)

            {

                if (ex.Number == 10060 || ex.Number == 64 || ex.Number == 10054) // it was 233

                {

                    //g.Msg("Connection to server is broken!", "Error");

                    bool b = Init(msServer, msIC, ref g.gS, ref g.gI);

                    if (!b)

                    {

                        if (g.Msg("Connection to the server are lost!\nDo you want to close application?", "Question", false)) { System.Windows.Forms.Application.Exit(); }

                    }

                    else

                    {

                        ex = null;

                        g.Msg("Software switch over the second connection to server!", "Info");

                        goto TryAgain;

                     //   return null;

                    }

                  return null;}

                else

                {

                    System.Windows.Forms.MessageBox.Show(ex.Message, "GetReader");

                    return null;

                }

           }

        }

Open in new window

0
Comment
Question by:dvplayltd
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 22

Expert Comment

by:8080_Diver
ID: 24800429
Short answer?  NO!
However, what you can do is wrapp the TRY CATCH in a WHILE that tests a bool variable (e.g. KeepTrying), that you created and set to True just for this purpose, and then, you can do something like increment an Attempts (int) variable and only set the KeepTrying variable to False when either the TRY part succeeds or the Catch part trys the maxmium number of times you want it to.
 
Something like the following:

  bool KeepTrying = ture;

  int  Attempts  = MAXATTEMPTS; 

  // note: set MAXATTEMPTS as a constant somewhere
 

  while (Keeptrying & (Attempts > 0)) do

  begin

    Attempts -= 1;

    try 

    {

      {put code here}

    }

    catch (Exception e)

    {

      if (Attempts = 0)

      {

         throw Exception.Create("ERROR: Attempts exceeded maximum " +

                                "allowed;\n\n" + e.Message);
 

      }

    }

  end

Open in new window

0
 
LVL 1

Accepted Solution

by:
fastpasscorp-sm earned 500 total points
ID: 24800540
Hi,

The answer is: in catch block you can write goto statement. Whenever you wrie any goto statement it will go to that label. But goto is possible within method, it is not possible to jump method to method.
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 24801560
When coding you should refrain from using GOTO. Make an attempt to rework your logic as suggested by 8080_Diver.

http://en.wikipedia.org/wiki/Goto
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 1

Expert Comment

by:fastpasscorp-sm
ID: 24801776
Actually I admit and honor your and 8080_Driver's comment. In my work I never use GOTO. I just  answer the question of dvplayltd.

0
 

Author Comment

by:dvplayltd
ID: 24802475
I'm far away of idea to pay tax "public opinion" I know about idea to not use GOTO at all, but this is for what I call "to be programmer on book"
I'm programmer in real world and from me are except working solution for short time and that is what I do. And I do it really good ..only with this project  will be working on 1000 + computers after 1 year.
I ask this question because I get some strange behavior which I test this & but look that this was because I change 20 and more times IP of my test server and he make some miss.
Now solution is apply , work OK and I see that problem was not that goto is not allowed to go to beginning from catch block.  Thanks to all gues for his option.



0
 

Author Closing Comment

by:dvplayltd
ID: 31600853
That is my ask and you answer of it, I ask only for technical side, not to be given advaice how to make my work harder . :-)
0
 
LVL 22

Expert Comment

by:8080_Diver
ID: 24802605
One of the first lessons I learned in becoming a developer was that poor code written for the sake of expedience tends to form habits of writing poor code while good coding habits are formed by writing good code.  It is rather like the paths worn in the grass by children walking to school . . . wherever you "walk" as a coder is where you will tend to wear a "path" and where you wear a "path" is where you will later "walk."
The problenm with using a GOTO in a catch is that you have short-circuited the Catch process.  You are turning a safety feature into a looping control . . . which is a very bad coding habit to form.  This will very likely introduce maintenance issues (if nothing else) because, when your code gets "cold" after 6 months or when someone else starts to work with it, it may well be assumed that a TRY . . . CATCH that is not in a usual looping control will only be executed once or it may be that someone introduces other code that should not be repeated into the space between the GOTO and where the GOTO goes to.
Now, if you wish to code like someone who is self taught and has no regard for maintenance or well written code, that is your choice; however, if your intention is to be taken seriously as a developer and to be able to write code that will be respected by fellow developers and that you can feel safe in letting others maintain, then I would recommend that you write code as though you were trying to impress your mentor.
will be working on 1000 + computers after 1 year
Especially  in this situation, you need to make sure that your code "follows the book" and that you code according to generally accepted standards of Best Coding Practices.  Do you really want to never be able to get away from this program?  
this is for what I call "to be programmer on book"
I am not at all sure what you mean by that phrase but if you mean that what I have suggested is "programming by the book", then there are far worse things to have said about your code.  Early in my career, I learned that one first programs "by the book" and then one learns when and how to "push the envelope" but pushing the envelope comes after one knows exactly what one is about to change and it is not done for exediency.
However, as I said earlier, it is your choice as to what coding habits you choose to form.
 
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now