簡體   English   中英

使用try-catch異常,如果發生異常,如何在捕獲括號內重新啟動程序?

[英]Using a try-catch exception, within the catch brackets how do I restart the program if an exception occurs?

我想做的是使用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  

}

當您開始學習編程時,您會發現可以使用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,則可能最終導致StackOverflowException :-D

只要是控制台應用程序,就可以在catch塊中調用Main方法。

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);
        }
    }
 }

但這不是一個好習慣。 您可以通過檢查應用程序中的用戶輸入來避免這種情況。

在始終對其進行操作之前,您應該考慮驗證輸入。 考慮創建一種專門的方法來接受用戶輸入並對其進行驗證。 該方法可以在內部繼續請求用戶輸入,直到驗證成功為止。

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

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

考慮只開始再次讀取輸入。 如果您需要它,那么以下內容將是合適的:

將方法getData()放入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循環使程序只要不正確就要求輸入。

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

   //clear the screen;

  //call the main method; 
  }
}

用戶數據輸入問題和程序執行異常之間存在很大差異,您應該有兩種獨立的機制來分別處理。

用戶數據輸入問題(例如,用戶輸入“ abc”(需要輸入數字))應由輸入驗證機制(由您編寫)處理。 用戶可以糾正這種類型的問題,通常會向用戶顯示驗證失敗的原因,並提供重新輸入數據的機會。

程序執行異常無法由用戶糾正(例如,嘗試連接數據庫時發生超時),應使用語言內置的try / catch機制進行處理。

由於多種原因,使用try / catch機制提供程序流控制(這是您試圖做的)被認為是較差的編程實踐。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM