Edit

Share via


FormatException Class

Definition

The exception that is thrown when the format of an argument is invalid, or when a composite format string is not well formed.

public class FormatException : Exception
public class FormatException : SystemException
[System.Serializable]
public class FormatException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class FormatException : SystemException
Inheritance
FormatException
Inheritance
FormatException
Derived
Attributes

Remarks

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

    • Boolean. The Boolean.Parse(String) and Convert.ToBoolean(String) methods require the string to be converted to be "True", "true", "False", or "false". Any other value throws a FormatException exception.

    • DateTime and DateTimeOffset. 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 the DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) and DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) methods, date and time data must also conform exactly to a pattern specified by one or more standard format strings or custom format strings that are provided as arguments in the method call. If it doesn't conform to an expected culture-specific pattern, a FormatException 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, see Parsing 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 the Guid.ToString method. For more information, see the Guid.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 a FormatException 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, see Parsing 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 a FormatException exception. For more information, see the documentation for the TimeSpan parsing method that threw the exception.

  • A type implements the 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.

    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()
    

    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.
    

    A FormatException exception can also be thrown by parsing methods, such as DateTime.ParseExact and Guid.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, the Guid structure's implementation of IFormattable 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()
    

    This exception also results from a coding error. To correct it, call a parsing method that doesn't require a precise format, such as DateTime.Parse or Guid.Parse, or substitute a valid format string. The following example corrects the error by calling the Guid.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-1ac5291c38cb
    
  • One or more of the indexes of the format items in a composite 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, and scale, so the code results in a FormatException 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()
    

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

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

    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);
    

    The exception is also thrown if your format string contains a typo. The following call to the String.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);
    

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

    String result = 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 the 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 Console.WriteLine(String, Object[]) method throws a FormatException exception, although the highest index of the format items is 3, and the parameter array of type Int32 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()
    

    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 = 2334
    

FormatException uses the HRESULT COR_E_FORMAT, which has the value 0x80131537.

The FormatException class derives from Exception and adds no unique members. For a list of initial property values for an instance of FormatException, see the FormatException constructors.

Constructors

FormatException()

Initializes a new instance of the FormatException class.

FormatException(SerializationInfo, StreamingContext)
Obsolete.

Initializes a new instance of the FormatException class with serialized data.

FormatException(String, Exception)

Initializes a new instance of the FormatException 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 the FormatException class with a specified error message.

Properties

Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink

Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException

Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message

Gets a message that describes the current exception.

(Inherited from Exception)
Source

Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace

Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite

Gets the method that throws the current exception.

(Inherited from Exception)

Methods

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException()

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)
Obsolete.

When overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception)
GetType()

Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Creates and returns a string representation of the current exception.

(Inherited from Exception)

Events

SerializeObjectState
Obsolete.

Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also