0

I wrote a console application in Python for a teacher a while ago, the usual grading calculations.This bit of code was preventing invalid input:

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

How does one Try/except ValueError in C#?

2 Answers 2

1
float Paper2;
while (true)
{
    try
    {
        Paper2 = float.Parse(Console.ReadLine());
        if (Paper2 > 10)
        {
            throw new Exception();
        }
        else
        {
            break;
        }
    }
    catch
    {
        Console.WriteLine("༼ つ ◕_◕ ༽つ error!");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Per Python Doc Try/except ValueError is for exception handling. You perform the same in C# using try .. catch block like

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

See more on Exceptions and Exception Handling

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.