使用try-catch异常,在catch括号中如果发生异常,如何重新启动程序?

时间:2012-10-27 11:18:51

标签: c# try-catch repeat

我要做的是使用try-catch异常来重新启动程序并让用户再次重新获取数据值。我该怎么做?我尝试使用goto将其恢复到第一行,但这似乎不起作用。 (并且普遍的共识是goto是邪恶的)。任何可以给予的帮助都非常感激。

Console.WriteLine("Please enter the two points that you wish to know the distance between:");
string point = Console.ReadLine();
string[] pointInput = point.Split(' ');


int pointNumber = Convert.ToInt16(pointInput[0]);                        //Stores the actual input number's into two integers
int pointNumber2 = Convert.ToInt16(pointInput[1]);

try                                                                      //Try-Catch statement to make sure that the User enters relevant PointNumbers
{
    double latitude = (Convert.ToDouble(items[pointNumber * 3]));            //
    double longtitude = (Convert.ToDouble(items[(pointNumber * 3) + 1]));    //
    double elevation = (Convert.ToDouble(items[(pointNumber * 3) + 2]));     //

    double latitude2 = (Convert.ToDouble(items[pointNumber2 * 3]));          //
    double longtitude2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 1]));  //
    double elevation2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 2]));   // Uses the relationship between the pointnumber and the array to select the required items from the array.


    //Calculate the distance between two point using the Distance class
    Console.WriteLine("The distance in km's to two decimal places is:");
    Distance curDistance = new Distance(latitude, longtitude, elevation, latitude2, longtitude2, elevation2);
    Console.WriteLine(String.Format("{0:0.00}", curDistance.toDistance()) + "km");
}
catch(IndexOutOfRangeException)
{

    Console.WriteLine("You have selected a point number outside the range of the data entered, please select two new pointnumbers");

  // here is where I would have the program restart  

}

7 个答案:

答案 0 :(得分:2)

当你开始学习编程时,你会发现使用while或do-while循环可以解决这些情况。因此,我会给你这样的答案:

            bool restart = false;
            do
            {
                restart = false;
                Console.WriteLine("Please enter the two points that you wish to know the distance between:");
                string point = Console.ReadLine();
                string[] pointInput = point.Split(' ');


                int pointNumber = Convert.ToInt16(pointInput[0]);                        //Stores the actual input number's into two integers
                int pointNumber2 = Convert.ToInt16(pointInput[1]);

                try                                                                      //Try-Catch statement to make sure that the User enters relevant PointNumbers
                {
                    double latitude = (Convert.ToDouble(items[pointNumber * 3]));            //
                    double longtitude = (Convert.ToDouble(items[(pointNumber * 3) + 1]));    //
                    double elevation = (Convert.ToDouble(items[(pointNumber * 3) + 2]));     //

                    double latitude2 = (Convert.ToDouble(items[pointNumber2 * 3]));          //
                    double longtitude2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 1]));  //
                    double elevation2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 2]));   // Uses the relationship between the pointnumber and the array to select the required items from the array.


                    //Calculate the distance between two point using the Distance class
                    Console.WriteLine("The distance in km's to two decimal places is:");
                    Distance curDistance = new Distance(latitude, longtitude, elevation, latitude2, longtitude2, elevation2);
                    Console.WriteLine(String.Format("{0:0.00}", curDistance.toDistance()) + "km");
                }
                catch (IndexOutOfRangeException)
                {

                    Console.WriteLine("You have selected a point number outside the range of the data entered, please select two new pointnumbers");
                    restart = true;
                }
            } while (restart);

注意如果你在Main中调用Main,你最终可能会产生StackOverflow异常:-D

答案 1 :(得分:1)

只要它是一个控制台应用程序,您就可以在Main块中调用catch方法。

private static int m_NumberOfRetries = 5; //Define how many times application can "restart" itself to avoid stackoverflow. 

static void Main(string[] args)
{
    try
    {
        //Do something useful
    }
    catch
    {
        m_NumberOfRetries--;
        if (m_NumberOfRetries != 0)
        {
            Main(args);
        }
    }
 }

但这样做并不是一个好习惯。您可以通过检查应用程序中的用户输入来避免这种情况。

答案 2 :(得分:1)

在进行操作之前,您应该考虑验证输入。考虑创建一个专门的方法来接受用户输入并验证它。该方法可以在内部继续询问用户输入,直到验证成功。

答案 3 :(得分:0)

// Starts a new instance of the program itself
System.Diagnostics.Process.Start(Application.ExecutablePath);

// Closes the current process
Environment.Exit(0);

答案 4 :(得分:0)

考虑只开始再次阅读输入。 如果这是您所需要的,以下是合适的:

将方法getData()放在Distance类中。类Distance必须具有非参数构造函数。

Distance.java

private double latitude;
private double longitude;
private double elevation;
private double latitude2;
private double longitude2;
private double elevation2;

public Distance() {}

public boolean getData(){
    Console.WriteLine("Please enter the two points that you wish to know the distance between:");
    string point = Console.ReadLine();
    string[] pointInput = point.Split(' ');
    int pointNumber = Convert.ToInt16(pointInput[0]);
    int pointNumber2 = Convert.ToInt16(pointInput[1]);
    try{
        latitude = (Convert.ToDouble(items[pointNumber * 3]));            //
        longtitude = (Convert.ToDouble(items[(pointNumber * 3) + 1]));    //
        elevation = (Convert.ToDouble(items[(pointNumber * 3) + 2]));     //

        latitude2 = (Convert.ToDouble(items[pointNumber2 * 3]));          //
        longtitude2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 1]));  //
        elevation2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 2]));   // I assume the exception goes from these 6 lines               

        return true;
    } catch (IndexOutOfRangeException) {
        return false;
    }
}

Main.java:

Distance curDistance = new Distance();
while(!curDistance.getData()) 
    Console.WriteLine("You have selected a point number outside the range of the data entered, please select two new pointnumbers"); 
Console.WriteLine("The distance in km's to two decimal places is:");   
Console.WriteLine(String.Format("{0:0.00}", curDistance.toDistance()) + "km");

while循环使程序只要输入错误就会询问输入。

答案 5 :(得分:0)

catch()
{
  console.writeline("Some error");
  private void restart()
   {
    //write Press any key to restart the program 

   //clear the screen;

  //call the main method; 
  }
}

答案 6 :(得分:0)

用户数据输入问题和程序执行异常存在很大差异,您应该有两个独立的机制来处理每个问题。

用户数据输入问题(例如用户输入需要编号的“abc”)应由输入验证机制(由您编写)处理。用户可以纠正这类问题,通常会向用户显示验证失败的原因,并为重新输入数据提供机会。

用户无法纠正程序执行异常(例如,尝试连接数据库时发生超时),应使用语言内置的try / catch机制进行处理。

由于多种原因,使用try / catch机制来提供程序流控制(这是你需要做的事情)被认为是糟糕的编程习惯。