抛出格式exceptionC#
我试图在有人试图输入非整数字符的实例中抛出格式exception。
Console.WriteLine("Your age:"); age = Int32.Parse(Console.ReadLine());
我不熟悉C#语言,可以使用帮助为这个实例编写try catch块。
非常感谢。
该代码已经抛出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 }
这避免了相当普通的用户错误情况的exception。
那这个呢:
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"); }
无需为该代码设置try catch块:
Console.WriteLine("Your age:"); int age; if (!Integer.TryParse(Console.ReadLine(), out age)) { throw new FormatException(); }