Skip to content

System.FormatException F# snippets #7727

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/example1.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
module example1

// <Snippet1>
open System

type TemperatureScale =
| Celsius = 0
| Fahrenheit = 1
| Kelvin = 2

let 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@()
// </Snippet1>
22 changes: 22 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/example2.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module example2

// <Snippet2>
open System

type TemperatureScale =
| Celsius = 0
| Fahrenheit = 1
| Kelvin = 2

let 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 Celsius
// </Snippet2>
19 changes: 19 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/example3.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module example3

open System

let n1 = 10
let n2 = 20
// <Snippet4>
let result = String.Format("{0} + {1} = {2}", n1, n2, n1 + n2)
// </Snippet4>
printfn $"{result}"

do
// <Snippet3>
let n1 = 10
let n2 = 20
String result = String.Format("{0 + {1] = {2}",
n1, n2, n1 + n2)
// </Snippet3>
|> ignore
19 changes: 19 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/fs.fsproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="example1.fs" />
<Compile Include="example2.fs" />
<Compile Include="example3.fs" />
<Compile Include="iformattable1.fs" />
<Compile Include="iformattable2.fs" />
<Compile Include="iformattable3.fs" />
<Compile Include="iformattable4.fs" />
<Compile Include="qa1.fs" />
<Compile Include="qa2.fs" />
<Compile Include="qa3.fs" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module ifromattable1

// <Snippet7>
let price = 169.32m
printfn $"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@()
// </Snippet7>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module iformattable2

// <Snippet8>
let price = 169.32m
printfn $"The cost is {price:C2}."
// The example displays the following output:
// The cost is $169.32.
// </Snippet8>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module iformattable3

// <Snippet9>
open System

let 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@()
// </Snippet9>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module iformattable4

// <Snippet10>
open System

let guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"
printfn $"{Guid.Parse guidString}"
// The example displays the following output:
// ba748d5c-ae5f-4cca-84e5-1ac5291c38cb
// </Snippet10>
24 changes: 24 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/qa1.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module qa1

// <Snippet5>
open System

let rnd = Random()
let numbers = Array.zeroCreate<int> 4
let mutable total = 0
for i = 0 to 2 do
let number = rnd.Next 1001
numbers[i] <- number
total <- 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 <StartupCode$fs>.$Example.main@()
// </Snippet5>
19 changes: 19 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/qa2.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module qa2

// <Snippet6>
open System

let rnd = Random()
let numbers = Array.zeroCreate<int> 4
let mutable total = 0
for i = 0 to 2 do
let number = rnd.Next 1001
numbers[i] <- number
total <- total + number
numbers[3] <- total
let values = Array.zeroCreate<obj> numbers.Length
numbers.CopyTo(values, 0)
Console.WriteLine("{0} + {1} + {2} = {3}", values)
// The example displays output like the following:
// 477 + 956 + 901 = 2334
// </Snippet6>
36 changes: 36 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/qa3.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
module qa3

open System

let willThrow () =
let nOpen = 1
let nClose = 2
// <Snippet23>
let result =
String.Format("The text has {0} '{' characters and {1} '}' characters.", nOpen, nClose)
// </Snippet23>
()

let wontThrow () =
let nOpen = 1
let nClose = 2
// <Snippet24>
let result =
String.Format("The text has {0} '{{' characters and {1} '}}' characters.", nOpen, nClose)
// </Snippet24>
()

let recommended () =
let nOpen = 1
let nClose = 2
// <Snippet25>
let result =
String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.", nOpen, "{", nClose, "}")
// </Snippet25>
()

willThrow ()
printfn ""
wontThrow ()
printfn ""
recommended ()
14 changes: 13 additions & 1 deletion xml/System/FormatException.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@

- 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 <xref:System.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 <xref:System.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 <xref:System.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.
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` (`try/with` in F#) block and handle the <xref:System.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 <xref:System.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 <xref:System> namespace can throw a <xref:System.FormatException> exception:

Expand All @@ -88,63 +88,75 @@
- A type implements the <xref:System.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](/dotnet/standard/base-types/standard-numeric-format-strings).

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/iformattable1.cs" id="Snippet7":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/iformattable1.fs" id="Snippet7":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/iformattable1.vb" id="Snippet7":::

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.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/iformattable2.cs" id="Snippet8":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/iformattable2.fs" id="Snippet8":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/iformattable2.vb" id="Snippet8":::

A <xref:System.FormatException> exception can also be thrown by parsing methods, such as <xref:System.DateTime.ParseExact%2A?displayProperty=nameWithType> and <xref:System.Guid.ParseExact%2A?displayProperty=nameWithType>, 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 <xref:System.Guid> structure's implementation of <xref:System.IFormattable> does not support the "G" format string.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/iformattable3.cs" id="Snippet9":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/iformattable3.fs" id="Snippet9":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/iformattable3.vb" id="Snippet9":::

This exception also results from a coding error. To correct it, call a parsing method that doesn't require a precise format, such as <xref:System.DateTime.Parse%2A?displayProperty=nameWithType> or <xref:System.Guid.Parse%2A?displayProperty=nameWithType>, or substitute a valid format string. The following example corrects the error by calling the <xref:System.Guid.Parse%2A?displayProperty=nameWithType> method.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/iformattable4.cs" interactive="try-dotnet" id="Snippet10":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/iformattable4.fs" id="Snippet10":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/iformattable4.vb" id="Snippet10":::

- One or more of the indexes of the format items in a [composite format string](/dotnet/standard/base-types/composite-formatting) 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 <xref:System.FormatException> exception at run time:.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/example1.cs" id="Snippet1":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/example1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/example1.vb" id="Snippet1":::

In this case, the <xref:System.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.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/example2.cs" id="Snippet2":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/example2.fs" id="Snippet2":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/example2.vb" id="Snippet2":::

- The composite format string isn't well-formed. When this happens, the <xref:System.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.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/qa3.cs" id="Snippet23":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/qa3.fs" id="Snippet23":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.String.Format/vb/qa3.vb" id="Snippet23":::

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.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/qa3.cs" interactive="try-dotnet-method" id="Snippet24":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/qa3.fs" id="Snippet24":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.String.Format/vb/qa3.vb" id="Snippet24":::

The exception is also thrown if your format string contains a typo. The following call to the <xref:System.String.Format%2A?displayProperty=nameWithType> method omits a closing brace and pairs an opening brace with a closing bracket.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/example3.cs" id="Snippet3":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/example3.fs" id="Snippet3":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/example3.vb" id="Snippet3":::

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

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/example3.cs" id="Snippet4":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/example3.fs" id="Snippet4":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/example3.vb" id="Snippet4":::

- You've supplied the object list in a composite formatting method as a strongly typed parameter array, and the <xref:System.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 <xref:System.Console.WriteLine%28System.String%2CSystem.Object%5B%5D%29?displayProperty=nameWithType> method throws a <xref:System.FormatException> exception, although the highest index of the format items is 3, and the parameter array of type <xref:System.Int32> has four elements.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/qa1.cs" id="Snippet5":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/qa1.fs" id="Snippet5":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/qa1.vb" id="Snippet5":::

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.

:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/qa2.cs" interactive="try-dotnet" id="Snippet6":::
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/qa2.fs" id="Snippet6":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/qa2.vb" id="Snippet6":::

<xref:System.FormatException> uses the HRESULT COR_E_FORMAT, which has the value 0x80131537.
Expand Down