Share via


疑難排解例外狀況:System.FormatException

當引數格式不符合方法的參數規格時,方法會擲回 FormatException 例外狀況 (Exception)。

例如,在 System 命名空間 (Namespace) 定義的資料型別中,許多資料型別都包含 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"))

相關秘訣

  • 請確定方法引數的格式正確。
    方法引數的格式,必須符合被叫用成員的參數規格。

請參閱

工作

HOW TO:使用例外狀況助理

參考

FormatException

Double.Parse

Boolean.Parse