diff --git a/snippets/fsharp/System/FormatException/Overview/example1.fs b/snippets/fsharp/System/FormatException/Overview/example1.fs new file mode 100644 index 00000000000..603355fcd86 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/example1.fs @@ -0,0 +1,30 @@ +module example1 + +// +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 .$Example.main@() +// \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/example2.fs b/snippets/fsharp/System/FormatException/Overview/example2.fs new file mode 100644 index 00000000000..00da029d444 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/example2.fs @@ -0,0 +1,22 @@ +module example2 + +// +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 +// \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/example3.fs b/snippets/fsharp/System/FormatException/Overview/example3.fs new file mode 100644 index 00000000000..4cfe19e6090 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/example3.fs @@ -0,0 +1,19 @@ +module example3 + +open System + +let n1 = 10 +let n2 = 20 +// +let result = String.Format("{0} + {1} = {2}", n1, n2, n1 + n2) +// +printfn $"{result}" + +do + // + let n1 = 10 + let n2 = 20 + String result = String.Format("{0 + {1] = {2}", + n1, n2, n1 + n2) + // + |> ignore \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/fs.fsproj b/snippets/fsharp/System/FormatException/Overview/fs.fsproj new file mode 100644 index 00000000000..3c58996b9b3 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/fs.fsproj @@ -0,0 +1,19 @@ + + + Exe + net6.0 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/iformattable1.fs b/snippets/fsharp/System/FormatException/Overview/iformattable1.fs new file mode 100644 index 00000000000..4404379d7f6 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/iformattable1.fs @@ -0,0 +1,17 @@ +module ifromattable1 + +// +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 .$Example.main@() +// \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/iformattable2.fs b/snippets/fsharp/System/FormatException/Overview/iformattable2.fs new file mode 100644 index 00000000000..024feb5f30a --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/iformattable2.fs @@ -0,0 +1,8 @@ +module iformattable2 + +// +let price = 169.32m +printfn $"The cost is {price:C2}." +// The example displays the following output: +// The cost is $169.32. +// \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/iformattable3.fs b/snippets/fsharp/System/FormatException/Overview/iformattable3.fs new file mode 100644 index 00000000000..d5039b382e6 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/iformattable3.fs @@ -0,0 +1,13 @@ +module iformattable3 + +// +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 .$Example.main@() +// \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/iformattable4.fs b/snippets/fsharp/System/FormatException/Overview/iformattable4.fs new file mode 100644 index 00000000000..76a551a06db --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/iformattable4.fs @@ -0,0 +1,10 @@ +module iformattable4 + +// +open System + +let guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb" +printfn $"{Guid.Parse guidString}" +// The example displays the following output: +// ba748d5c-ae5f-4cca-84e5-1ac5291c38cb +// \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/qa1.fs b/snippets/fsharp/System/FormatException/Overview/qa1.fs new file mode 100644 index 00000000000..9baa4b21784 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/qa1.fs @@ -0,0 +1,24 @@ +module qa1 + +// +open System + +let rnd = Random() +let numbers = Array.zeroCreate 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 .$Example.main@() +// \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/qa2.fs b/snippets/fsharp/System/FormatException/Overview/qa2.fs new file mode 100644 index 00000000000..e89bb960d13 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/qa2.fs @@ -0,0 +1,19 @@ +module qa2 + +// +open System + +let rnd = Random() +let numbers = Array.zeroCreate 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 numbers.Length +numbers.CopyTo(values, 0) +Console.WriteLine("{0} + {1} + {2} = {3}", values) +// The example displays output like the following: +// 477 + 956 + 901 = 2334 +// \ No newline at end of file diff --git a/snippets/fsharp/System/FormatException/Overview/qa3.fs b/snippets/fsharp/System/FormatException/Overview/qa3.fs new file mode 100644 index 00000000000..3a48f6593d9 --- /dev/null +++ b/snippets/fsharp/System/FormatException/Overview/qa3.fs @@ -0,0 +1,36 @@ +module qa3 + +open System + +let willThrow () = + let nOpen = 1 + let nClose = 2 + // + let result = + String.Format("The text has {0} '{' characters and {1} '}' characters.", nOpen, nClose) + // + () + +let wontThrow () = + let nOpen = 1 + let nClose = 2 + // + let result = + String.Format("The text has {0} '{{' characters and {1} '}}' characters.", nOpen, nClose) + // + () + +let recommended () = + let nOpen = 1 + let nClose = 2 + // + let result = + String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.", nOpen, "{", nClose, "}") + // + () + +willThrow () +printfn "" +wontThrow () +printfn "" +recommended () diff --git a/xml/System/FormatException.xml b/xml/System/FormatException.xml index e099a19205a..1c868652729 100644 --- a/xml/System/FormatException.xml +++ b/xml/System/FormatException.xml @@ -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 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 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 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 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 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 namespace can throw a exception: @@ -88,31 +88,37 @@ - A type implements the 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 exception can also be thrown by parsing methods, such as and , 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 structure's implementation of 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 or , or substitute a valid format string. The following example corrects the error by calling the 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 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 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 exception is always a result of developer error. It should be corrected rather than handled in a `try/catch` block. @@ -120,31 +126,37 @@ 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 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 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 method throws a exception, although the highest index of the format items is 3, and the parameter array of type 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"::: uses the HRESULT COR_E_FORMAT, which has the value 0x80131537.