错误的用户输入C#/ Python

时间:2016-02-27 23:55:53

标签: c# python input

我刚才用Python为老师写了一个控制台应用程序,这是通常的评分计算。这段代码阻止了无效输入:

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

C#中的Try/except ValueError怎么样?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

Python Doc Try/except ValueError用于异常处理。您使用C#阻止{/ 1}}在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