FormatException Class

The exception that is thrown when the format of an argument is invalid, or when a composite format string is not well formed.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class FormatException _
	Inherits SystemException

The FormatException type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFormatExceptionInitializes a new instance of the FormatException class.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFormatException(String)Initializes a new instance of the FormatException class with a specified error message.
Protected methodFormatException(SerializationInfo, StreamingContext)Initializes a new instance of the FormatException class with serialized data.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFormatException(String, Exception)Initializes a new instance of the FormatException class with a specified error message and a reference to the inner exception that is the cause of this exception.
Top

  NameDescription
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsDataGets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsHelpLinkGets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsHResultGets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsInnerExceptionGets the Exception instance that caused the current exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMessageGets a message that describes the current exception. (Inherited from Exception.)
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsSourceGets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsStackTraceGets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public propertyTargetSiteGets the method that throws the current exception. (Inherited from Exception.)
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetBaseExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetObjectDataWhen overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the runtime type of the current instance. (Inherited from Exception.)

In XNA Framework 3.0, this member is inherited from Object.GetType.


In Portable Class Library Portable Class Library, this member is inherited from Object.GetType.


In .NET for Windows Store apps Windows 8, this member is inherited from Object.GetType.
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringCreates and returns a string representation of the current exception. (Inherited from Exception.)
Top

  NameDescription
Protected eventSerializeObjectStateOccurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top

A FormatException exception can be thrown for one of the following reasons:

  • In a call to a method that converts a string to some other data type, the string doesn't conform to the required pattern. This typically occurs when calling some methods of the Convert class and the Parse and ParseExact methods of some types.

    In most cases, particularly if the string that you're converting is input by a user or read from a file, you should use a try/catch block and handle the FormatException exception if the conversion is unsuccessful. You can also replace the call to the conversion method with a call to a TryParse or TryParseExact method, if one exists. However, a FormatException exception that is thrown when you're trying to parse a predefined or hard-coded string indicates a program error. In this case, you should correct the error rather than handle the exception.

    The conversion of a string to the following types in the System namespace can throw a FormatException exception:

    • Boolean. The Boolean.Parse(String) and Convert.ToBoolean(String) methods require the string to be converted to be "True", "true", "False", or "false". Any other value throws a FormatException exception.

    • DateTime and DateTimeOffset. All date and time data is interpreted based on the formatting conventions of a particular culture: either the current thread culture (or, in some cases, the current application domain culture), the invariant culture, or a specified culture. When you call the DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) and DateTimeOffset.ParseExact(String, String(), IFormatProvider, DateTimeStyles) methods, date and time data must also conform exactly to a pattern specified by one or more standard format strings or custom format strings that are provided as arguments in the method call. If it doesn't conform to an expected culture-specific pattern, a FormatException exception is thrown. This means that date and time data saved in a culture-specific format on one system might not parse successfully on another system.

      For more information about parsing dates and times, see Parsing Date and Time Strings in the .NET Framework and the documentation for the method that threw the exception.

    • GUIDs. The string representation of a GUID must consist of 32 hexadecimal digits (0-F), and must be in one of the five formats output by the Guid.ToString method. For more information, see the Guid.Parse method.

    • Numeric types, including all signed integers, unsigned integers, and floating-point types. The string to be parsed must consist of the Latin digits 0-9. A positive or negative sign, decimal separator, group separators, and currency symbol may also be permitted. Trying to parse a string that contains any other character always throws a FormatException exception.

      All numeric strings are interpreted based on the formatting conventions of a particular culture: either the current thread culture (or, in some cases, the current application domain culture), the invariant culture, or a specified culture. As a result, a numeric string that is parsed by using the conventions of one culture might fail when using the conventions of another.

      For more information about parsing numeric strings, see Parsing Numeric Strings in the .NET Framework and the documentation for the specific method that threw the exception.

    • Time intervals. The string to be parsed must be either in fixed culture-insensitive format or in a culture-sensitive format defined by the current thread culture (or, in some cases, the current application domain culture), the invariant culture, or a specified culture. If the string isn't in an appropriate format, or if, at the minimum, the days, hours, and minutes components of the time interval aren't present, the parsing method throws a FormatException exception. For more information, see the documentation for the TimeSpan parsing method that threw the exception.

  • A type implements the IFormattable interface, which supports format strings that define how an object is converted to its string representation, and an invalid format string is used. This is most common in a formatting operation. In the following example, the "Q" standard format string is used in a composite format string to format a number. However, "Q" is not a valid standard format string.

    Module Example
       Public Sub Main()
          Dim price As Decimal = 169.32d
          Console.WriteLine("The cost is {0:Q2}.", price)
       End Sub 
    End Module 
    ' The example displays the following output: 
    '    Unhandled Exception: System.FormatException: Format specifier was invalid. 
    '       at System.Number.FormatDecimal(Decimal value, String format, NumberFormatInfo info) 
    '       at System.Decimal.ToString(String format, IFormatProvider provider) 
    '       at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) 
    '       at System.IO.TextWriter.WriteLine(String format, Object arg0) 
    '       at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0) 
    '       at Example.Main()
    

    This exception results from a coding error. To correct the error, either remove the format string or substitute a valid one. The following example corrects the error by replacing the invalid format string with the "C" (currency) format string.

    Module Example
       Public Sub Main()
          Dim price As Decimal = 169.32d
          Console.WriteLine("The cost is {0:C2}.", price)
       End Sub 
    End Module 
    ' The example displays the following output: 
    '   The cost is $169.32.
    

    A FormatException exception can also be thrown by parsing methods, such as DateTime.ParseExact and Guid.ParseExact, that require the string to be parsed to conform exactly to the pattern specified by a format string. In the following example, the string representation of a GUID is expected to conform to the pattern specified by the "G" standard format string. However, the Guid structure's implementation of IFormattable does not support the "G" format string.

    Module Example
       Public Sub Main()
          Dim guidString As String = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"
          Console.WriteLine(Guid.ParseExact(guidString, "G"))
       End Sub 
    End Module 
    ' The example displays the following output: 
    '    Unhandled Exception: System.FormatException:  
    '       Format String can be only "D", "d", "N", "n", "P", "p", "B", "b", "X" or "x". 
    '       at System.Guid.ParseExact(String input, String format) 
    '       at Example.Main()
    

    This exception also results from a coding error. To correct it, call a parsing method that doesn’t require a precise format, such as DateTime.Parse or Guid.Parse, or substitute a valid format string. The following example corrects the error by calling the Guid.Parse method.

    Module Example
       Public Sub Main()
          Dim guidString As String = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"
          Console.WriteLine(Guid.Parse(guidString))
       End Sub 
    End Module 
    ' The example displays the following output: 
    '   ba748d5c-ae5f-4cca-84e5-1ac5291c38cb
    
  • One or more of the indexes of the format items in a composite format string is greater than the indexes of the items in the object list or parameter array. In the following example, the largest index of a format item in the format string is 3. Because the indexes of items in the object list are zero-based, this format string would require the object list to have four items. Instead, it has only three, dat, temp, and scale, so the code results in a FormatException exception at run time:.

    Module Example
       Public Enum TemperatureScale As Integer
          Celsius
          Fahrenheit
          Kelvin
       End Enum 
    
       Public Sub Main()
          Dim info As String = GetCurrentTemperature()
          Console.WriteLine(info)
       End Sub 
    
       Private Function GetCurrentTemperature() As String 
          Dim dat As Date = Date.Now
          Dim temp As Decimal = 20.6d
          Dim scale As TemperatureScale = TemperatureScale.Celsius
          Dim result As String 
    
          result = String.Format("At {0:t} on {1:D}, the temperature is {2:F1} {3:G}",
                                 dat, temp, scale)    
          Return result
       End Function 
    End Module 
    ' The example displays output like the following: 
    '    Unhandled Exception: System.FormatException: Format specifier was invalid. 
    '       at System.Number.FormatDecimal(Decimal value, String format, NumberFormatInfo info) 
    '       at System.Decimal.ToString(String format, IFormatProvider provider) 
    '       at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) 
    '       at System.String.Format(IFormatProvider provider, String format, Object[] args) 
    '       at Example.Main()
    

    In this case, the FormatException exception is a result of developer error. It should be corrected rather than handled in a try/catch block by making sure that each item in the object list corresponds to the index of a format item. To correct this example, change the index of the second format item to refer to the dat variable, and decrement the index of each subsequent format item by one.

    Module Example
       Public Enum TemperatureScale As Integer
          Celsius
          Fahrenheit
          Kelvin
       End Enum 
    
       Public Sub Main()
          Dim info As String = GetCurrentTemperature()
          Console.WriteLine(info)
       End Sub 
    
       Private Function GetCurrentTemperature() As String 
          Dim dat As Date = Date.Now
          Dim temp As Decimal = 20.6d
          Dim scale As TemperatureScale = TemperatureScale.Celsius
          Dim result As String 
    
          result = String.Format("At {0:t} on {0:D}, the temperature is {1:F1} {2:G}",
                                 dat, temp, scale)    
          Return result
       End Function 
    End Module 
    ' The example displays output like the following: 
    '       At 10:40 AM on Wednesday, June 04, 2014, the temperature is 20.6 Celsius
    
  • The composite format string isn't well-formed. When this happens, the FormatException exception is always a result of developer error. It should be corrected rather than handled in a try/catch block.

    Trying to include literal braces in a string, as the following example does, will throw the exception.

    result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
                           nOpen, nClose)
    

    The recommended technique for including literal braces in a composite format string is to include them in the object list and use format items to insert them into the result string. For example, you can modify the previous composite format string as shown here.

    result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
                           nOpen, nClose)
    

    The exception is also thrown if your format string contains a typo. The following call to the String.Format method omits a closing brace and pairs an opening brace with a closing bracket.

    Dim n1 As Integer = 10
    Dim n2 As Integer = 20
    Dim result As String = String.Format("{0 + {1] = {2}", 
                                         n1, n2, n1 + n2)
    

    To correct the error, ensure that all opening and closing braces correspond.

    Dim result As String = String.Format("{0} + {1} = {2}", 
                                         n1, n2, n1 + n2)
    
  • You've supplied the object list in a composite formatting method as a strongly typed parameter array, and the FormatException exception indicates that the index of one or more format items exceeds the number of arguments in the object list. This occurs because no explicit conversion between array types exists, so instead the compiler treats the array as a single argument rather than as a parameter array. For example, the following call to the Console.WriteLine(String, Object()) method throws a FormatException exception, although the highest index of the format items is 3, and the parameter array of type Int32 has four elements.

    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim numbers(3) As Integer 
          Dim total As Integer = 0
          For ctr = 0 To 2
             Dim number As Integer = rnd.Next(1001)
             numbers(ctr) = number
             total += number
          Next
          numbers(3) = total
          Console.WriteLine("{0} + {1} + {2} = {3}", numbers)   
       End Sub 
    End Module 
    ' The example displays the following output: 
    '    Unhandled Exception:  
    '    System.FormatException:  
    '       Index (zero based) must be greater than or equal to zero and less than the size of the argument list. 
    '       at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) 
    '       at System.IO.TextWriter.WriteLine(String format, Object arg0) 
    '       at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0) 
    '       at Example.Main()
    

    Instead of handling this exception, you should eliminate its cause. Because neither Visual Basic nor C# can convert an integer array to an object array, you have to perform the conversion yourself before calling the composite formatting method. The following example provides one implementation.

    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim numbers(3) As Integer 
          Dim total As Integer = 0
          For ctr = 0 To 2
             Dim number As Integer = rnd.Next(1001)
             numbers(ctr) = number
             total += number
          Next
          numbers(3) = total
          Dim values(numbers.Length - 1) As Object
          numbers.CopyTo(values, 0) 
          Console.WriteLine("{0} + {1} + {2} = {3}", values)   
       End Sub 
    End Module 
    ' The example displays output like the following: 
    '       477 + 956 + 901 = 2334
    

FormatException uses the HRESULT COR_E_FORMAT, which has the value 0x80131537.

The FormatException class derives from Exception and adds no unique members. For a list of initial property values for an instance of FormatException, see the FormatException constructors.

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft