Partager via


Troubleshooting Exceptions: System.FormatException

A FormatException exception is thrown by a method that parses or formats a type when the format of an argument does not meet the parameter specifications of the method.

Causing Format Exceptions

Formatting

Formatting is the process of converting an instance of a class, structure, or enumeration value to its string representation, often so that the resulting string can be displayed to users or be used to save the state of the object.

For example, Int32.ToString(String) takes a string parameter that identifies a standard or custom format string and returns the string representation of the number. The method throws a FormatException If the format string is invalid or not supported, a is thrown.

Composite Formatting

Composite formatting takes a list of objects and a composite format string as input. A composite format string consists of fixed text intermixed with indexed placeholders, called format items, that correspond to the objects in the list. The formatting operation yields a result string that consists of the original fixed text intermixed with the string representation of the objects in the list.

String.Format and Console.WriteLine are examples of methods that do composite formatting. Methods that use composite formatting throw a FormatException if the format string is invalid or the index of a format item is less than zero, or greater than or equal to the number of arguments.

Parsing

Parsing is the process of converting a string that represents a .NET Framework base type into that base type. For example, a parsing operation is used to convert a string to a floating-point number or to a date and time value.

For example, Int32.Parse(String)Parse converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information specified in the IformatProvider parameter. If the string is not in the correct format, FormatException is thrown.

Avoiding FormatExceptions

The FormatException class reference article includes the common causes and solutions of FormatException errors.

The MSDN Library sections Formatting Types in the .NET Framework and Parsing Strings in the .NET Framework contain information about correctly formatting and parsing types.

Composite formatting

Composite Formatting

Numeric types

Standard Numeric Format Strings

Custom Numeric Format Strings

Parsing Numeric Strings in the .NET Framework

Date and Time and Timespan types

Standard Date and Time Format Strings

Custom Date and Time Format Strings

Standard TimeSpan Format Strings

Custom TimeSpan Format Strings

Parsing Date and Time Strings in the .NET Framework

Other types

Enumeration Format Strings

Parsing Other Strings in the .NET Framework