C# 中的 FormatException

csharpprogrammingserver side programming

当参数格式无效时,会抛出 FomatException。

让我们看一个例子。

当我们将 int 以外的值设置为 int.Parse() 方法时,会抛出 FormatException,如下所示 −

示例

using System;
class Demo {
   static void Main() {
      string str = "3.5";
      int res = int.Parse(str);
   }
}

由于我们传递了除整数以外的值,编译上述程序时会抛出以下错误。

输出

Unhandled Exception:
System.FormatException: Input string was not in a correct format.

相关文章