【问题标题】:Throw a format exception C#抛出格式异常 C#
【发布时间】:2012-09-23 06:19:08
【问题描述】:

我试图在有人在提示输入年龄时尝试输入非整数字符的情况下引发格式异常。

        Console.WriteLine("Your age:");
        age = Int32.Parse(Console.ReadLine());

我不熟悉 C# 语言,可以使用帮助来为此实例编写 try catch 块。

非常感谢。

【问题讨论】:

  • Int32.Parse 将抛出一个 FormatException 如果一个非数字字符串被传递给它 - 你的代码看起来像你想要的那样?
  • 你的意思是你试图catch 一个格式异常?
  • Int32.Parse 可能返回三种不同的异常

标签: c# try-catch formatexception


【解决方案1】:

该代码已经抛出FormatException。如果你的意思是你想抓住它,你可以写:

Console.WriteLine("Your age:");
string line = Console.ReadLine();
try
{
    age = Int32.Parse(line);
}
catch (FormatException)
{
    Console.WriteLine("{0} is not an integer", line);
    // Return? Loop round? Whatever.
}

但是,使用int.TryParse更好

Console.WriteLine("Your age:");
string line = Console.ReadLine();
if (!int.TryParse(line, out age))
{
    Console.WriteLine("{0} is not an integer", line);
    // Whatever
}

这避免了相当普通的用户错误情况的异常。

【讨论】:

  • 我对这行有点困惑:if (!int.TryParse(line, out age)
  • @user1513637:以什么方式? int.TryParse 返回是否成功,并将结果存储在out 参数中。有关详细信息,请参阅文档。
【解决方案2】:

这个呢:

Console.WriteLine("Your age:");
try
{    
     age = Int32.Parse(Console.ReadLine());
}
catch(FormatException e)
{
    MessageBox.Show("You have entered non-numeric characters");
   //Console.WriteLine("You have entered non-numeric characters");
}

【讨论】:

    【解决方案3】:

    不需要为该代码设置 try catch 块:

    Console.WriteLine("Your age:");
    int age;
    if (!Integer.TryParse(Console.ReadLine(), out age))
    {
        throw new FormatException();
    }
    

    【讨论】:

      【解决方案4】:

      你可以这样做......

      int age;
      

      Console.WriteLine("你的年龄:"); age=Conver.ToInt32(Console.Readline());

      //@Erfunll

      【讨论】:

      • 原作者正在寻求有关如何编写 try/catch 的帮助。通过向他展示如何执行此操作,您的答案可能会得到改善。
      • 您好,欢迎来到 Stack Overflow!请拨打tour。感谢您的回答,但您是否还可以添加有关您的代码如何解决问题的解释?另外,请查看help center 以获取有关如何格式化代码的信息。
      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多