This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
The exception that is thrown when the format of an argument is invalid, or when acomposite format string is not well formed.
public ref class FormatException : Exceptionpublic ref class FormatException : SystemExceptionpublic class FormatException : Exceptionpublic class FormatException : SystemException[System.Serializable]public class FormatException : SystemException[System.Serializable][System.Runtime.InteropServices.ComVisible(true)]public class FormatException : SystemExceptiontype FormatException = class inherit Exceptiontype FormatException = class inherit SystemException[<System.Serializable>]type FormatException = class inherit SystemException[<System.Serializable>][<System.Runtime.InteropServices.ComVisible(true)>]type FormatException = class inherit SystemExceptionPublic Class FormatExceptionInherits ExceptionPublic Class FormatExceptionInherits SystemExceptionAFormatException 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 theConvert class and theParse andParseExact 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 atry/catch (try/with in F#) block and handle theFormatException exception if the conversion is unsuccessful. You can also replace the call to the conversion method with a call to aTryParse orTryParseExact method, if one exists. However, aFormatException 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 theSystem namespace can throw aFormatException exception:
Boolean. TheBoolean.Parse(String) andConvert.ToBoolean(String) methods require the string to be converted to be "True", "true", "False", or "false". Any other value throws aFormatException exception.
DateTime andDateTimeOffset. All date and time data is interpreted based on the formatting conventions of a particular culture: either the current culture (or, in some cases, the current application domain culture), the invariant culture, or a specified culture. When you call theDateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) andDateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) methods, date and time data must also conformexactly to a pattern specified by one or morestandard format strings orcustom format strings that are provided as arguments in the method call. If it doesn't conform to an expected culture-specific pattern, aFormatException 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, seeParsing Date and Time Strings 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 theGuid.ToString method. For more information, see theGuid.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 aFormatException exception.
All numeric strings are interpreted based on the formatting conventions of a particular culture: either the current 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, seeParsing Numeric Strings 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 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 aFormatException exception. For more information, see the documentation for theTimeSpan parsing method that threw the exception.
A type implements theIFormattable 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 validstandard format string.
using System;public class Example{ public static void Main() { decimal price = 169.32m; Console.WriteLine("The cost is {0:Q2}.", price); }}// 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()let price = 169.32mprintfn $"The cost is {price:Q2}."// The example displays the following output:// Unhandled Exception: System.FormatException: Format specifier was invalid.// at System.Number.NumberToString(ValueStringBuilder& sb, NumberBuffer& number, Char format, Int32 nMaxDigits, NumberFormatInfo info)// at System.Number.TryFormatDecimal(Decimal value, ReadOnlySpan`1 format, NumberFormatInfo info, Span`1 destination, Int32& charsWritten)// at System.Decimal.TryFormat(Span`1 destination, Int32& charsWritten, ReadOnlySpan`1 format, IFormatProvider provider)// at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)// at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)// at Microsoft.FSharp.Core.PrintfImpl.InterpolandToString@917.Invoke(Object vobj)// at Microsoft.FSharp.Core.PrintfImpl.PrintfEnv`3.RunSteps(Object[] args, Type[] argTys, Step[] steps)// at Microsoft.FSharp.Core.PrintfModule.gprintf[a,TState,TResidue,TResult,TPrinter](FSharpFunc`2 envf, PrintfFormat`4 format)// at <StartupCode$fs>.$Example.main@()Module Example Public Sub Main() Dim price As Decimal = 169.32d Console.WriteLine("The cost is {0:Q2}.", price) End SubEnd 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.
using System;public class Example{ public static void Main() { decimal price = 169.32m; Console.WriteLine("The cost is {0:C2}.", price); }}// The example displays the following output:// The cost is $169.32.let price = 169.32mprintfn $"The cost is {price:C2}."// The example displays the following output:// The cost is $169.32.Module Example Public Sub Main() Dim price As Decimal = 169.32d Console.WriteLine("The cost is {0:C2}.", price) End SubEnd Module' The example displays the following output:' The cost is $169.32.AFormatException exception can also be thrown by parsing methods, such asDateTime.ParseExact andGuid.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, theGuid structure's implementation ofIFormattable does not support the "G" format string.
using System;public class Example{ public static void Main() { string guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"; Console.WriteLine(Guid.ParseExact(guidString, "G")); }}// 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()open Systemlet guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"printfn $"""{Guid.ParseExact(guidString, "G")}"""// 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 <StartupCode$fs>.$Example.main@()Module Example Public Sub Main() Dim guidString As String = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb" Console.WriteLine(Guid.ParseExact(guidString, "G")) End SubEnd 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 asDateTime.Parse orGuid.Parse, or substitute a valid format string. The following example corrects the error by calling theGuid.Parse method.
using System;public class Example{ public static void Main() { string guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"; Console.WriteLine(Guid.Parse(guidString)); }}// The example displays the following output:// ba748d5c-ae5f-4cca-84e5-1ac5291c38cbopen Systemlet guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"printfn $"{Guid.Parse guidString}"// The example displays the following output:// ba748d5c-ae5f-4cca-84e5-1ac5291c38cbModule Example Public Sub Main() Dim guidString As String = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb" Console.WriteLine(Guid.Parse(guidString)) End SubEnd Module' The example displays the following output:' ba748d5c-ae5f-4cca-84e5-1ac5291c38cbOne or more of the indexes of the format items in acomposite 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, andscale, so the code results in aFormatException exception at run time:.
using System;public class Example{ public enum TemperatureScale { Celsius, Fahrenheit, Kelvin } public static void Main() { String info = GetCurrentTemperature(); Console.WriteLine(info); } private static String GetCurrentTemperature() { DateTime dat = DateTime.Now; Decimal temp = 20.6m; TemperatureScale scale = TemperatureScale.Celsius; String result; result = String.Format("At {0:t} on {1:D}, the temperature is {2:F1} {3:G}", dat, temp, scale); return result; }}// 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()open Systemtype TemperatureScale = | Celsius = 0 | Fahrenheit = 1 | Kelvin = 2let getCurrentTemperature () = let dat = DateTime.Now let temp = 20.6m let scale = TemperatureScale.Celsius String.Format("At {0:t} on {1:D}, the temperature is {2:F1} {3:G}", dat, temp, scale)getCurrentTemperature ()|> printfn "%s"// The example displays output like the following:// Unhandled Exception: System.FormatException: Format specifier was invalid.// at System.Number.NumberToString(ValueStringBuilder& sb, NumberBuffer& number, Char format, Int32 nMaxDigits, NumberFormatInfo info) // at System.Number.TryFormatDecimal(Decimal value, ReadOnlySpan`1 format, NumberFormatInfo info, Span`1 destination, Int32& charsWritten)// at System.Decimal.TryFormat(Span`1 destination, Int32& charsWritten, ReadOnlySpan`1 format, IFormatProvider provider) // at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)// at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)// at System.String.Format(String format, Object arg0, Object arg1, Object arg2)// at Example.getCurrentTemperature()// at <StartupCode$fs>.$Example.main@()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 FunctionEnd 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, theFormatException exception is a result of developer error. It should be corrected rather than handled in atry/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 thedat variable, and decrement the index of each subsequent format item by one.
using System;public class Example{ public enum TemperatureScale { Celsius, Fahrenheit, Kelvin } public static void Main() { String info = GetCurrentTemperature(); Console.WriteLine(info); } private static String GetCurrentTemperature() { DateTime dat = DateTime.Now; Decimal temp = 20.6m; TemperatureScale scale = TemperatureScale.Celsius; String result; result = String.Format("At {0:t} on {0:D}, the temperature is {1:F1} {2:G}", dat, temp, scale); return result; }}// The example displays output like the following:// At 10:40 AM on Wednesday, June 04, 2014, the temperature is 20.6 Celsiusopen Systemtype TemperatureScale = | Celsius = 0 | Fahrenheit = 1 | Kelvin = 2let getCurrentTemperature () = let dat = DateTime.Now let temp = 20.6m let scale = TemperatureScale.Celsius String.Format("At {0:t} on {0:D}, the temperature is {1:F1} {2:G}", dat, temp, scale)getCurrentTemperature ()|> printfn "%s"// The example displays output like the following:// At 10:40 AM on Wednesday, June 04, 2014, the temperature is 20.6 CelsiusModule 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 FunctionEnd Module' The example displays output like the following:' At 10:40 AM on Wednesday, June 04, 2014, the temperature is 20.6 CelsiusThe composite format string isn't well-formed. When this happens, theFormatException exception is always a result of developer error. It should be corrected rather than handled in atry/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);let result = String.Format("The text has {0} '{' characters and {1} '}' characters.", nOpen, nClose)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.
string result;int nOpen = 1;int nClose = 2;result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.", nOpen, nClose);Console.WriteLine(result);let result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.", nOpen, nClose)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 theString.Format method omits a closing brace and pairs an opening brace with a closing bracket.
int n1 = 10;int n2 = 20;String result = String.Format("{0 + {1] = {2}", n1, n2, n1 + n2);let n1 = 10let n2 = 20String result = String.Format("{0 + {1] = {2}", n1, n2, n1 + n2)Dim n1 As Integer = 10Dim n2 As Integer = 20Dim result As String = String.Format("{0 + {1] = {2}", n1, n2, n1 + n2)To correct the error, ensure that all opening and closing braces correspond.
String result = String.Format("{0} + {1} = {2}", n1, n2, n1 + n2);let result = String.Format("{0} + {1} = {2}", n1, n2, n1 + n2)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 theFormatException 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 theConsole.WriteLine(String, Object[]) method throws aFormatException exception, although the highest index of the format items is 3, and the parameter array of typeInt32 has four elements.
using System;using System.Collections.Generic;public class Example{ public static void Main() { Random rnd = new Random(); int[] numbers = new int[4]; int total = 0; for (int ctr = 0; ctr <= 2; ctr++) { int number = rnd.Next(1001); numbers[ctr] = number; total += number; } numbers[3] = total; Console.WriteLine("{0} + {1} + {2} = {3}", numbers); }}// 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()open Systemlet rnd = Random()let numbers = Array.zeroCreate<int> 4let mutable total = 0for i = 0 to 2 do let number = rnd.Next 1001 numbers[i] <- number total <- total + numbernumbers[3] <- totalConsole.WriteLine("{0} + {1} + {2} = {3}", numbers)// 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 <StartupCode$fs>.$Example.main@()Imports System.Collections.GenericModule 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 SubEnd 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.
using System;using System.Collections.Generic;public class Example{ public static void Main() { Random rnd = new Random(); int[] numbers = new int[4]; int total = 0; for (int ctr = 0; ctr <= 2; ctr++) { int number = rnd.Next(1001); numbers[ctr] = number; total += number; } numbers[3] = total; object[] values = new object[numbers.Length]; numbers.CopyTo(values, 0); Console.WriteLine("{0} + {1} + {2} = {3}", values); }}// The example displays output like the following:// 477 + 956 + 901 = 2334open Systemlet rnd = Random()let numbers = Array.zeroCreate<int> 4let mutable total = 0for i = 0 to 2 do let number = rnd.Next 1001 numbers[i] <- number total <- total + numbernumbers[3] <- totallet values = Array.zeroCreate<obj> numbers.Lengthnumbers.CopyTo(values, 0)Console.WriteLine("{0} + {1} + {2} = {3}", values)// The example displays output like the following:// 477 + 956 + 901 = 2334Imports System.Collections.GenericModule 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 SubEnd Module' The example displays output like the following:' 477 + 956 + 901 = 2334FormatException uses the HRESULT COR_E_FORMAT, which has the value 0x80131537.
TheFormatException class derives fromException and adds no unique members. For a list of initial property values for an instance ofFormatException, see theFormatException constructors.
| Name | Description |
|---|---|
| FormatException() | Initializes a new instance of theFormatException class. |
| FormatException(SerializationInfo, StreamingContext) | Obsolete. Initializes a new instance of theFormatException class with serialized data. |
| FormatException(String, Exception) | Initializes a new instance of theFormatException class with a specified error message and a reference to the inner exception that is the cause of this exception. |
| FormatException(String) | Initializes a new instance of theFormatException class with a specified error message. |
| Name | Description |
|---|---|
| Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited fromException) |
| HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited fromException) |
| HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited fromException) |
| InnerException | Gets theException instance that caused the current exception. (Inherited fromException) |
| Message | Gets a message that describes the current exception. (Inherited fromException) |
| Source | Gets or sets the name of the application or the object that causes the error. (Inherited fromException) |
| StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited fromException) |
| TargetSite | Gets the method that throws the current exception. (Inherited fromException) |
| Name | Description |
|---|---|
| Equals(Object) | Determines whether the specified object is equal to the current object. (Inherited fromObject) |
| GetBaseException() | When overridden in a derived class, returns theException that is the root cause of one or more subsequent exceptions. (Inherited fromException) |
| GetHashCode() | Serves as the default hash function. (Inherited fromObject) |
| GetObjectData(SerializationInfo, StreamingContext) | Obsolete. When overridden in a derived class, sets theSerializationInfo with information about the exception. (Inherited fromException) |
| GetType() | Gets the runtime type of the current instance. (Inherited fromException) |
| MemberwiseClone() | Creates a shallow copy of the currentObject. (Inherited fromObject) |
| ToString() | Creates and returns a string representation of the current exception. (Inherited fromException) |
| Name | Description |
|---|---|
| SerializeObjectState | Obsolete. Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited fromException) |
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?