Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3956181

Browse files
authored
System.FormatException F# snippets (#7727)
* FormatException F# snippets * fix project file
1 parent 8e005e9 commit 3956181

File tree

12 files changed

+230
-1
lines changed

12 files changed

+230
-1
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
module example1
2+
3+
// <Snippet1>
4+
open System
5+
6+
type TemperatureScale =
7+
| Celsius = 0
8+
| Fahrenheit = 1
9+
| Kelvin = 2
10+
11+
let getCurrentTemperature () =
12+
let dat = DateTime.Now
13+
let temp = 20.6m
14+
let scale = TemperatureScale.Celsius
15+
String.Format("At {0:t} on {1:D}, the temperature is {2:F1} {3:G}", dat, temp, scale)
16+
17+
getCurrentTemperature ()
18+
|> printfn "%s"
19+
20+
// The example displays output like the following:
21+
// Unhandled Exception: System.FormatException: Format specifier was invalid.
22+
// at System.Number.NumberToString(ValueStringBuilder& sb, NumberBuffer& number, Char format, Int32 nMaxDigits, NumberFormatInfo info)
23+
// at System.Number.TryFormatDecimal(Decimal value, ReadOnlySpan`1 format, NumberFormatInfo info, Span`1 destination, Int32& charsWritten)
24+
// at System.Decimal.TryFormat(Span`1 destination, Int32& charsWritten, ReadOnlySpan`1 format, IFormatProvider provider)
25+
// at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
26+
// at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
27+
// at System.String.Format(String format, Object arg0, Object arg1, Object arg2)
28+
// at Example.getCurrentTemperature()
29+
// at <StartupCode$fs>.$Example.main@()
30+
// </Snippet1>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
module example2
2+
3+
// <Snippet2>
4+
open System
5+
6+
type TemperatureScale =
7+
| Celsius = 0
8+
| Fahrenheit = 1
9+
| Kelvin = 2
10+
11+
let getCurrentTemperature () =
12+
let dat = DateTime.Now
13+
let temp = 20.6m
14+
let scale = TemperatureScale.Celsius
15+
String.Format("At {0:t} on {0:D}, the temperature is {1:F1} {2:G}", dat, temp, scale)
16+
17+
getCurrentTemperature ()
18+
|> printfn "%s"
19+
20+
// The example displays output like the following:
21+
// At 10:40 AM on Wednesday, June 04, 2014, the temperature is 20.6 Celsius
22+
// </Snippet2>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
module example3
2+
3+
open System
4+
5+
let n1 = 10
6+
let n2 = 20
7+
// <Snippet4>
8+
let result = String.Format("{0} + {1} = {2}", n1, n2, n1 + n2)
9+
// </Snippet4>
10+
printfn $"{result}"
11+
12+
do
13+
// <Snippet3>
14+
let n1 = 10
15+
let n2 = 20
16+
String result = String.Format("{0 + {1] = {2}",
17+
n1, n2, n1 + n2)
18+
// </Snippet3>
19+
|> ignore
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<OutputType>Exe</OutputType>
4+
<TargetFramework>net6.0</TargetFramework>
5+
</PropertyGroup>
6+
7+
<ItemGroup>
8+
<Compile Include="example1.fs" />
9+
<Compile Include="example2.fs" />
10+
<Compile Include="example3.fs" />
11+
<Compile Include="iformattable1.fs" />
12+
<Compile Include="iformattable2.fs" />
13+
<Compile Include="iformattable3.fs" />
14+
<Compile Include="iformattable4.fs" />
15+
<Compile Include="qa1.fs" />
16+
<Compile Include="qa2.fs" />
17+
<Compile Include="qa3.fs" />
18+
</ItemGroup>
19+
</Project>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
module ifromattable1
2+
3+
// <Snippet7>
4+
let price = 169.32m
5+
printfn $"The cost is {price:Q2}."
6+
// The example displays the following output:
7+
// Unhandled Exception: System.FormatException: Format specifier was invalid.
8+
// at System.Number.NumberToString(ValueStringBuilder& sb, NumberBuffer& number, Char format, Int32 nMaxDigits, NumberFormatInfo info)
9+
// at System.Number.TryFormatDecimal(Decimal value, ReadOnlySpan`1 format, NumberFormatInfo info, Span`1 destination, Int32& charsWritten)
10+
// at System.Decimal.TryFormat(Span`1 destination, Int32& charsWritten, ReadOnlySpan`1 format, IFormatProvider provider)
11+
// at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
12+
// at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
13+
// at [email protected](Object vobj)
14+
// at Microsoft.FSharp.Core.PrintfImpl.PrintfEnv`3.RunSteps(Object[] args, Type[] argTys, Step[] steps)
15+
// at Microsoft.FSharp.Core.PrintfModule.gprintf[a,TState,TResidue,TResult,TPrinter](FSharpFunc`2 envf, PrintfFormat`4 format)
16+
// at <StartupCode$fs>.$Example.main@()
17+
// </Snippet7>
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module iformattable2
2+
3+
// <Snippet8>
4+
let price = 169.32m
5+
printfn $"The cost is {price:C2}."
6+
// The example displays the following output:
7+
// The cost is $169.32.
8+
// </Snippet8>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
module iformattable3
2+
3+
// <Snippet9>
4+
open System
5+
6+
let guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"
7+
printfn $"""{Guid.ParseExact(guidString, "G")}"""
8+
// The example displays the following output:
9+
// Unhandled Exception: System.FormatException:
10+
// Format String can be only "D", "d", "N", "n", "P", "p", "B", "b", "X" or "x".
11+
// at System.Guid.ParseExact(String input, String format)
12+
// at <StartupCode$fs>.$Example.main@()
13+
// </Snippet9>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module iformattable4
2+
3+
// <Snippet10>
4+
open System
5+
6+
let guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"
7+
printfn $"{Guid.Parse guidString}"
8+
// The example displays the following output:
9+
// ba748d5c-ae5f-4cca-84e5-1ac5291c38cb
10+
// </Snippet10>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
module qa1
2+
3+
// <Snippet5>
4+
open System
5+
6+
let rnd = Random()
7+
let numbers = Array.zeroCreate<int> 4
8+
let mutable total = 0
9+
for i = 0 to 2 do
10+
let number = rnd.Next 1001
11+
numbers[i] <- number
12+
total <- total + number
13+
numbers[3] <- total
14+
Console.WriteLine("{0} + {1} + {2} = {3}", numbers)
15+
16+
// The example displays the following output:
17+
// Unhandled Exception:
18+
// System.FormatException:
19+
// Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
20+
// at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
21+
// at System.IO.TextWriter.WriteLine(String format, Object arg0)
22+
// at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0)
23+
// at <StartupCode$fs>.$Example.main@()
24+
// </Snippet5>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
module qa2
2+
3+
// <Snippet6>
4+
open System
5+
6+
let rnd = Random()
7+
let numbers = Array.zeroCreate<int> 4
8+
let mutable total = 0
9+
for i = 0 to 2 do
10+
let number = rnd.Next 1001
11+
numbers[i] <- number
12+
total <- total + number
13+
numbers[3] <- total
14+
let values = Array.zeroCreate<obj> numbers.Length
15+
numbers.CopyTo(values, 0)
16+
Console.WriteLine("{0} + {1} + {2} = {3}", values)
17+
// The example displays output like the following:
18+
// 477 + 956 + 901 = 2334
19+
// </Snippet6>
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
module qa3
2+
3+
open System
4+
5+
let willThrow () =
6+
let nOpen = 1
7+
let nClose = 2
8+
// <Snippet23>
9+
let result =
10+
String.Format("The text has {0} '{' characters and {1} '}' characters.", nOpen, nClose)
11+
// </Snippet23>
12+
()
13+
14+
let wontThrow () =
15+
let nOpen = 1
16+
let nClose = 2
17+
// <Snippet24>
18+
let result =
19+
String.Format("The text has {0} '{{' characters and {1} '}}' characters.", nOpen, nClose)
20+
// </Snippet24>
21+
()
22+
23+
let recommended () =
24+
let nOpen = 1
25+
let nClose = 2
26+
// <Snippet25>
27+
let result =
28+
String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.", nOpen, "{", nClose, "}")
29+
// </Snippet25>
30+
()
31+
32+
willThrow ()
33+
printfn ""
34+
wontThrow ()
35+
printfn ""
36+
recommended ()

xml/System/FormatException.xml

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@
6565
6666
- 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.
6767
68-
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.
68+
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.
6969
7070
The conversion of a string to the following types in the <xref:System> namespace can throw a <xref:System.FormatException> exception:
7171
@@ -88,63 +88,75 @@
8888
- 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).
8989
9090
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/iformattable1.cs" id="Snippet7":::
91+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/iformattable1.fs" id="Snippet7":::
9192
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/iformattable1.vb" id="Snippet7":::
9293
9394
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.
9495
9596
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/iformattable2.cs" id="Snippet8":::
97+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/iformattable2.fs" id="Snippet8":::
9698
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/iformattable2.vb" id="Snippet8":::
9799
98100
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.
99101
100102
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/iformattable3.cs" id="Snippet9":::
103+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/iformattable3.fs" id="Snippet9":::
101104
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/iformattable3.vb" id="Snippet9":::
102105
103106
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.
104107
105108
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/iformattable4.cs" interactive="try-dotnet" id="Snippet10":::
109+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/iformattable4.fs" id="Snippet10":::
106110
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/iformattable4.vb" id="Snippet10":::
107111
108112
- 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:.
109113
110114
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/example1.cs" id="Snippet1":::
115+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/example1.fs" id="Snippet1":::
111116
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/example1.vb" id="Snippet1":::
112117
113118
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.
114119
115120
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/example2.cs" id="Snippet2":::
121+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/example2.fs" id="Snippet2":::
116122
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/example2.vb" id="Snippet2":::
117123
118124
- 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.
119125
120126
Trying to include literal braces in a string, as the following example does, will throw the exception.
121127
122128
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/qa3.cs" id="Snippet23":::
129+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/qa3.fs" id="Snippet23":::
123130
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.String.Format/vb/qa3.vb" id="Snippet23":::
124131
125132
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.
126133
127134
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/qa3.cs" interactive="try-dotnet-method" id="Snippet24":::
135+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/qa3.fs" id="Snippet24":::
128136
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.String.Format/vb/qa3.vb" id="Snippet24":::
129137
130138
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.
131139
132140
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/example3.cs" id="Snippet3":::
141+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/example3.fs" id="Snippet3":::
133142
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/example3.vb" id="Snippet3":::
134143
135144
To correct the error, ensure that all opening and closing braces correspond.
136145
137146
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/example3.cs" id="Snippet4":::
147+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/example3.fs" id="Snippet4":::
138148
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/example3.vb" id="Snippet4":::
139149
140150
- 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.
141151
142152
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/qa1.cs" id="Snippet5":::
153+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/qa1.fs" id="Snippet5":::
143154
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/qa1.vb" id="Snippet5":::
144155
145156
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.
146157
147158
:::code language="csharp" source="~/snippets/csharp/System/FormatException/Overview/qa2.cs" interactive="try-dotnet" id="Snippet6":::
159+
:::code language="fsharp" source="~/snippets/fsharp/System/FormatException/Overview/qa2.fs" id="Snippet6":::
148160
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.formatexception/vb/qa2.vb" id="Snippet6":::
149161
150162
<xref:System.FormatException> uses the HRESULT COR_E_FORMAT, which has the value 0x80131537.

0 commit comments

Comments
 (0)