【发布时间】:2021-06-22 02:40:36
【问题描述】:
在使用catch() 函数发现错误后,我正在尝试重新启动我的程序,但我也希望它显示错误,停止程序的其余部分运行,然后重新启动程序。
这只是我用作示例的代码的缩短版本。
using System;
namespace Calculator
{
internal class Program
{
private static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}
当它说
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
break; 使其余代码停止,并显示错误。这很好,但是程序也在那之后结束,我想要的是程序在错误后重复。有什么办法可以发生这种情况,但它允许 1)Console.WriteLine("Please enter a number");,2)程序不运行其余代码(我们被要求提供第二个值的部分),以及 3)程序重新开始。如果这没有意义,请告诉我,因为这很难解释。 :)
【问题讨论】:
-
这能回答你的问题吗? Try-Catch with Do-While loop
-
与您的问题无关...不要在
try/catch中使用float.Parse,而是使用float.TryParse。异常很重,应该只用于异常的情况。用户输入错误的数据几乎没有例外。