关于异常的疑难解答:System.FormatException

当某个实参的格式不符合方法的形参规范时,该方法会引发 FormatException 异常。

例如,在 System 命名空间中定义的许多数据类型都包含一个 Parse 方法,该方法采用字符串参数并将其转换为数据类型。 如果所提供的参数的格式无法转换,这些方法会引发 FormatException。 如果字符串参数的格式不是可识别的数字格式,Double.Parse 将引发 FormatException。 请看下面的示例。

' The first three statements run correctly.

Console.WriteLine(Double.Parse("32,115"))

Console.WriteLine(Double.Parse("32115"))

Console.WriteLine(Double.Parse("32.115"))

' The following statement throws a FormatException.

' Console.WriteLine(Double.Parse("32 115"))

同样,如果字符串参数不是“True”或“False”,Boolean.Parse 会引发此异常。

' This statement runs correctly.

Console.WriteLine(Boolean.Parse("True"))

' This statement throws a FormatException.

' Console.WriteLine(Boolean.Parse("Ture"))

相关提示

  • 请确保方法参数的格式正确。
    方法参数的格式必须符合调用的成员的参数规范。

请参见

任务

如何:使用异常助手

参考

FormatException

Double.Parse

Boolean.Parse