2012-10-27 44 views
0

這段代碼只是拋出異常,因爲短sNum被分配了int num的大範圍值,並且轉換失敗。任何方式。 我想要循環請求,直到輸入有效的短促響應。循環輸入請求,直到有效數字被接受

static void Main() 
    { 
     int num = 40000; 
     short sNum = 0; 
     try 
     { 
      sNum = Convert.ToInt16(num); 

     } 
     catch (OverflowException ex) 
     { 
      // Request for input until no exception thrown. 
      Console.WriteLine(ex.Message); 
      sNum = Convert.ToInt16(Console.ReadLine()); 
     } 

     Console.WriteLine("output is {0}",sNum); 
         Console.ReadLine(); 
    } 

謝謝。

+0

查找了'while'循環。 – John3136

+0

「循環請求」是什麼意思?並短暫進入如何?由用戶? – nawfal

+0

使用TryParse(http://msdn.microsoft.com/en-us/library/9hh1awhy%28v=vs.100%29.aspx)是一個異常處理程序和一個while循環(http://www.dotnetperls。 COM /時)。 – TToni

回答

5

原因是當您的catch塊內的轉換失敗時,您拋出異常。技術上catch塊在try塊之外,所以它不會像你認爲的那樣被catch所捕獲。這看起來並不像你希望的那樣循環。

例外通常不被認爲是代碼中正常(非例外)事件的最佳方法。在這種情況下,TryParse方法和循環會更好。

static void Main() 
{ 
    string input = //get your user input; 
    short sNum = 0; 

    while(!short.TryParse(input,out sNum)) 
    { 
     Console.WriteLine("Input invalid, please try again"); 
     input = //get your user input; 
    } 

    Console.WriteLine("output is {0}",sNum); 
    Console.ReadLine(); 
} 
0
short sNum; 
string input; 

do 
{ 
    input = Console.ReadLine(); 
} while (!Int16.TryParse(input, out sNum)) 

Console.WriteLine("output is {0}", sNum); 
相關問題