2016-02-27 50 views
0

我前一段時間寫的Python中的控制檯應用程序的老師,代碼通常分級calculations.This位是防止無效輸入:錯誤用戶輸入C#/ Python的

while True: 
    try:  
     Paper2 = float(input("Enter grade: ")) 
    except ValueError: 
     print ("༼ つ ◕_◕ ༽つ error!") 
     continue  
    if Paper2 > 10: 
     print ("༼ つ ◕_◕ ༽つ error!") 
     continue 
    else: 
     break 

如何做一個Try/except ValueError在C# ?

回答

1
float Paper2; 
while (true) 
{ 
    try 
    { 
     Paper2 = float.Parse(Console.ReadLine()); 
     if (Paper2 > 10) 
     { 
      throw new Exception(); 
     } 
     else 
     { 
      break; 
     } 
    } 
    catch 
    { 
     Console.WriteLine("༼ つ ◕_◕ ༽つ error!"); 
    } 
} 
0

Python DocTry/except ValueError用於異常處理。您在使用C#執行相同try .. catch塊像

try 
{ 
    // your code logic which may raise exception 
} 
catch(Exception ex) 
{ 
//handle the exception do necessary stuff like logging 
} 
finally 
{ 
//perform cleanup here 
} 

查看更多關於Exceptions and Exception Handling