About System.FormatException exception

What is FormatException

Invalid parameter format or a composite format string exception that is thrown when incorrectly.

inherit
Object
Exception
SystemException
FormatException

Detailed description

One of the following reasons may cause an exception: FormatException

  • In the call to convert the string data to other types of methods, the string does not meet the desired mode. This usually occurs when calling Convert certain methods and certain types of class ParseExact Parsetime and method.

    In most cases, especially when the string to be converted is a user input or read from a file, use the try/catchblock and FormatException handle exceptions (if conversion is not successful). You can also call will be replaced for the conversion method TryParseor TryParseExactmethod call (if present). However, FormatException when you try to analyze pre-defined or hard-coded strings thrown exception indicates a program error. In this case, you should correct this error, rather than handle the exception.

    To convert a string System name the following types of space may FormatException throw an exception:

      • Boolean . Boolean.Parse (String) and Convert.ToBoolean (String) The method of claim convert the string to "true", "true", "false" or "false". Any other value will FormatException throw an exception.

      • DateTime and DateTimeOffset . All date and time data are based on a specific culture formatting conventions: the current thread culture (or culture for the current application domain in some cases), or a specified fixed regional culture. Call DateTime.ParseExact (String, String, the IFormatProvider, the DateTimeStyles) DateTimeOffset.ParseExact (String, String [], the IFormatProvider, the DateTimeStyles) time and method, date and time data must completely match the standard format or a string of one or more custom format string (as provided in the parameter) mode call the specified method. If it does not meet the expectations of the culture-specific pattern, FormatException exception is thrown. This means that the system is saved on a specific analysis may not be successful on other systems in regional date and time data format.

        For more information about the date and time of the analysis, see the documentation date and time strings and analysis method throws an exception.

      • GUID. String representation of a GUID must contain 32 hexadecimal digit (0-F), and must be made Guid.ToString of the five methods of the output format. For more information, see Guid.Parse method.

      • Numeric type, including all signed integer, unsigned integer and floating-point type. The string to be analyzed must contain Latin digits 0-9. It may also allow the use of positive or negative sign, decimal separator, set separators, and currency symbols. Try to analyze any string that contains other characters always caused FormatException exception.

        All figures are based on the specific culture string formatting conventions: the current thread culture (or in some cases for the current application domain culture), or a specified fixed regional culture. Therefore, the use of another regional convention analysis of numerical strings may fail.

        For more information about the analysis of numerical strings, see String analysis and numerical methods of documentation for the specific trigger abnormal.

      • time interval. String must be analyzed using culture-insensitive culture-sensitive format or the format defined by the current thread culture (in some cases for the current application domain culture), or a specified fixed regional culture . If the format string is not correct, or if the minimum time interval, the number of portions of days, hours and minutes do not exist, the analysis method throws FormatException exception. For more information, please refer to throw an exception TimeSpan document analysis methods.

  • Type implements IFormattable interface, which supports the definition of how to convert an object to its string representation, using the format string invalid format string. This is most common in the formatting operation. In the following example, a "Q" in the composite string format standard format to format string values. However, "Q" is not a valid standard format strings.

    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 is caused by a coding error. To correct this error, delete or replace the format string valid string. The following example to correct errors by replacing invalid format string using 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.

    The method may further analysis ( DateTime.ParseExact such and Guid.ParseExact raise an exception), which requires analysis of the string, to comply with the format string specified pattern. FormatException In the following example, GUID string representation should be consistent with "G" standard format strings specified pattern. However, the Guid Structure IFormattable implementation does not support the format string "G".

    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 due to coding errors. To correct this error analysis, does not require precise format of the call (e.g. DateTime.Parse or Guid.Parse ) or alternatively a valid format string. The following example by calling Guid.Parse to correct the error 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
  • A composite format item format string index is greater than one or more parameters of the object list or index entry in the array. In the following example, the maximum index format entry format string 3. Since the object list index entries are zero, and therefore requires this format string having four object list. On the contrary, it has only three, dat tempand scale, therefore, the code at runtime FormatException cause an exception:

    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 FormatException , exceptions are errors caused by the developer. This situation should be corrected, rather than through try/catch, rather than being processed in block format to ensure that the index entry corresponding to each entry in the object list. To correct this example, a second set of index entries to form data reference variable, and each subsequent index entry format minus 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
  • Format composite format string is incorrect. When this happens FormatException , an exception is always a developer error. This situation should be corrected, but not the try/catchprocessed block.

    As shown in the following example, it contains text braces attempts cause an exception in the string.

    result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
                           nOpen, nClose);
    Recommended method comprising braces in the composite format string is contained in the object list them, and insert them using the format entry into the result string. For example, you can modify the format string of a composite, as shown below.
    string result;
    int nOpen = 1;
    int nClose = 2;
    result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
                           nOpen, nClose);
    Console.WriteLine(result);
    If the format string contains typographical errors, also throws an exception. The following of String.Format omitted right brace called method, and the big left and right parentheses pair.
    int n1 = 10;
    int n2 = 20;
    String result = String.Format("{0 + {1] = {2}", 
                                  n1, n2, n1 + n2);

    To correct this error, make sure that all left brace and right brace correspondence.

    String result = String.Format("{0} + {1} = {2}", 
                                  n1, n2, n1 + n2);
  • Provided a composite object list formatting method in strongly typed as a parameter array, but FormatException abnormality index represents one or more format items exceeds the number of parameters in the object list. This occurs because there is no explicit conversions between array type, so the compiler as a single array parameter instead of an array as a parameter. For example, the following pair Console.WriteLine (String, Object []) method call will FormatException throws an exception, although the format of the highest index entry is 3, and the type Int32 parameter array having 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()
    The reason should be eliminated, instead of dealing with this exception. Since neither Visual Basic C # array of integers can not be converted to an array of objects, it is necessary to perform the conversion yourself before the composite formatting method call. The following examples provide an 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

HRESULT

FormatException using COR_E_FORMAT value of HRESULT 0x80131537.

Guess you like

Origin www.cnblogs.com/yilang/p/12060989.html