FormatException Klasa

Definicja

Wyjątek zgłaszany, gdy format argumentu jest nieprawidłowy lub gdy ciąg formatu złożonego nie jest dobrze sformułowany.

public ref class FormatException : Exception
public ref class FormatException : SystemException
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
type FormatException = class
    inherit Exception
type FormatException = class
    inherit SystemException
[<System.Serializable>]
type FormatException = class
    inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type FormatException = class
    inherit SystemException
Public Class FormatException
Inherits Exception
Public Class FormatException
Inherits SystemException
Dziedziczenie
FormatException
Dziedziczenie
FormatException
Pochodne
Atrybuty

Uwagi

Wyjątek FormatException można zgłosić z jednego z następujących powodów:

  • W wywołaniu metody, która konwertuje ciąg na inny typ danych, ciąg nie jest zgodny z wymaganym wzorcem. Zwykle występuje to podczas wywoływania niektórych metod Convert klasy i metod i Parse ParseExact niektórych typów.

    W większości przypadków, szczególnie jeśli ciąg, który konwertujesz, jest wejściowy przez użytkownika lub odczyt z pliku, należy użyć try/catch bloku (try/with w języku F#) i obsłużyć FormatException wyjątek, jeśli konwersja nie powiedzie się. Możesz również zastąpić wywołanie metody konwersji wywołaniem metody TryParse lub TryParseExact , jeśli istnieje. FormatException Jednak wyjątek zgłaszany podczas próby przeanalizowania wstępnie zdefiniowanego lub zakodowanego ciągu wskazuje błąd programu. W takim przypadku należy poprawić błąd, a nie obsługiwać wyjątku.

    Konwersja ciągu na następujące typy w System przestrzeni nazw może zgłosić FormatException wyjątek:

    • Boolean. Metody Boolean.Parse(String) i Convert.ToBoolean(String) wymagają przekonwertowania ciągu na wartość "True", "true", "false" lub "false". Każda inna wartość zgłasza FormatException wyjątek.

    • DateTime i DateTimeOffset. Wszystkie dane daty i godziny są interpretowane na podstawie konwencji formatowania określonej kultury: bieżącej kultury (lub w niektórych przypadkach bieżącej kultury domeny aplikacji), niezmiennej kultury lub określonej kultury. Podczas wywoływania DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) metod i DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) dane daty i godziny muszą być również zgodne z wzorcem określonym przez co najmniej jeden standardowy ciąg formatu lub niestandardowe ciągi formatu , które są udostępniane jako argumenty w wywołaniu metody. Jeśli nie jest zgodny z oczekiwanym wzorcem specyficznym dla kultury, FormatException zgłaszany jest wyjątek. Oznacza to, że dane daty i godziny zapisane w formacie specyficznym dla kultury w jednym systemie mogą nie zostać pomyślnie przeanalizowane w innym systemie.

      Aby uzyskać więcej informacji na temat analizowania dat i godzin, zobacz Analizowanie ciągów daty i godziny oraz dokumentację metody, która zwróciła wyjątek.

    • Identyfikatory guid. Reprezentacja ciągu identyfikatora GUID musi składać się z 32 cyfr szesnastkowych (0-F) i musi znajdować się w jednym z pięciu formatów wyjściowych metody Guid.ToString . Aby uzyskać więcej informacji, zobacz metodę Guid.Parse .

    • Typy liczbowe, w tym wszystkie podpisane liczby całkowite, niepodpisane liczby całkowite i typy zmiennoprzecinkowe. Ciąg, który ma być analizowany, musi składać się z cyfr łacińskich 0–9. Może być również dozwolony znak dodatni lub ujemny, separator dziesiętny, separatory grup i symbol waluty. Próba przeanalizowania ciągu zawierającego dowolny inny znak zawsze zgłasza FormatException wyjątek.

      Wszystkie ciągi liczbowe są interpretowane na podstawie konwencji formatowania określonej kultury: bieżącej kultury, niezmiennej kultury lub określonej kultury. W związku z tym ciąg liczbowy, który jest analizowany przy użyciu konwencji jednej kultury, może zakończyć się niepowodzeniem podczas korzystania z konwencji innej.

      Aby uzyskać więcej informacji na temat analizowania ciągów liczbowych, zobacz Analizowanie ciągów liczbowych i dokumentację dla określonej metody, która zwróciła wyjątek.

    • Interwały czasu. Ciąg, który ma być analizowany, musi być w formacie bez uwzględniania kultury lub w formacie wrażliwym na kulturę zdefiniowanym przez bieżącą kulturę, niezmienną kulturę lub określoną kulturę. Jeśli ciąg nie jest w odpowiednim formacie lub jeśli co najmniej dni, godziny i minuty składników interwału czasu nie są obecne, metoda analizowania zgłasza FormatException wyjątek. Aby uzyskać więcej informacji, zobacz dokumentację TimeSpan metody analizowania, która zwróciła wyjątek.

  • Typ implementuje IFormattable interfejs, który obsługuje ciągi formatu definiujące sposób konwertowania obiektu na reprezentację ciągu, a używany jest nieprawidłowy ciąg formatu. Jest to najczęściej spotykane w operacji formatowania. W poniższym przykładzie ciąg formatu standardowego "Q" jest używany w ciągu formatu złożonego do formatowania liczby. Jednak ciąg "Q" nie jest prawidłowym ciągiem formatu standardowego.

    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()
    
    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@()
    
    Module Example
       Public Sub Main()
          Dim price As Decimal = 169.32d
          Console.WriteLine("The cost is {0:Q2}.", price)
       End Sub
    End Module
    ' 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()
    

    Ten wyjątek wynika z błędu kodowania. Aby naprawić błąd, usuń ciąg formatu lub zastąp prawidłowy. Poniższy przykład poprawia błąd, zastępując nieprawidłowy ciąg formatu ciągiem "C" (waluta).

    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.
    
    let price = 169.32m
    printfn $"The cost is {price:C2}."
    // The example displays the following output:
    //    The cost is $169.32.
    
    Module Example
       Public Sub Main()
          Dim price As Decimal = 169.32d
          Console.WriteLine("The cost is {0:C2}.", price)
       End Sub
    End Module
    ' The example displays the following output:
    '   The cost is $169.32.
    

    Wyjątek FormatException można również zgłosić przez metody analizowania, takie jak DateTime.ParseExact i Guid.ParseExact, które wymagają analizy ciągu w celu zachowania zgodności dokładnie ze wzorcem określonym przez ciąg formatu. W poniższym przykładzie oczekuje się, że reprezentacja ciągu identyfikatora GUID jest zgodna ze wzorcem określonym przez ciąg formatu standardowego "G". Guid Jednak implementacja IFormattable struktury nie obsługuje ciągu formatu "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()
    
    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@()
    
    Module Example
       Public Sub Main()
          Dim guidString As String = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"
          Console.WriteLine(Guid.ParseExact(guidString, "G"))
       End Sub
    End Module
    ' 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()
    

    Ten wyjątek wynika również z błędu kodowania. Aby to poprawić, wywołaj metodę analizowania, która nie wymaga dokładnego formatu, takiego jak DateTime.Parse lub , Guid.Parselub zastąp prawidłowy ciąg formatu. Poniższy przykład poprawia błąd przez wywołanie Guid.Parse metody .

    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
    
    open System
    
    let guidString = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"
    printfn $"{Guid.Parse guidString}"
    // The example displays the following output:
    //    ba748d5c-ae5f-4cca-84e5-1ac5291c38cb
    
    Module Example
       Public Sub Main()
          Dim guidString As String = "ba748d5c-ae5f-4cca-84e5-1ac5291c38cb"
          Console.WriteLine(Guid.Parse(guidString))
       End Sub
    End Module
    ' The example displays the following output:
    '   ba748d5c-ae5f-4cca-84e5-1ac5291c38cb
    
  • Co najmniej jeden indeks elementów formatu w ciągu formatu złożonego jest większy niż indeksy elementów na liście obiektów lub tablicy parametrów. W poniższym przykładzie największy indeks elementu formatu w ciągu formatu wynosi 3. Ponieważ indeksy elementów na liście obiektów są oparte na zera, ten ciąg formatu wymaga, aby lista obiektów miała cztery elementy. Zamiast tego ma tylko trzy, dat, tempi scale, więc kod powoduje wyjątek w FormatException czasie wykonywania:.

    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()
    
    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@()
    
    Module Example
       Public Enum TemperatureScale As Integer
          Celsius
          Fahrenheit
          Kelvin
       End Enum
    
       Public Sub Main()
          Dim info As String = GetCurrentTemperature()
          Console.WriteLine(info)
       End Sub
    
       Private Function GetCurrentTemperature() As String
          Dim dat As Date = Date.Now
          Dim temp As Decimal = 20.6d
          Dim scale As TemperatureScale = TemperatureScale.Celsius
          Dim result As String 
          
          result = String.Format("At {0:t} on {1:D}, the temperature is {2:F1} {3:G}",
                                 dat, temp, scale)    
          Return result
       End Function
    End Module
    ' 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()
    

    W takim przypadku FormatException wyjątek jest wynikiem błędu dewelopera. Należy go poprawić, a nie obsłużyć w try/catch bloku, upewniając się, że każdy element na liście obiektów odpowiada indeksowi elementu formatu. Aby poprawić ten przykład, zmień indeks drugiego elementu formatu, aby odwoływać się do dat zmiennej, i zdekrementować indeks każdego kolejnego elementu formatu o jeden.

    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
    
    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
    
    Module Example
       Public Enum TemperatureScale As Integer
          Celsius
          Fahrenheit
          Kelvin
       End Enum
    
       Public Sub Main()
          Dim info As String = GetCurrentTemperature()
          Console.WriteLine(info)
       End Sub
    
       Private Function GetCurrentTemperature() As String
          Dim dat As Date = Date.Now
          Dim temp As Decimal = 20.6d
          Dim scale As TemperatureScale = TemperatureScale.Celsius
          Dim result As String 
          
          result = String.Format("At {0:t} on {0:D}, the temperature is {1:F1} {2:G}",
                                 dat, temp, scale)    
          Return result
       End Function
    End Module
    ' The example displays output like the following:
    '       At 10:40 AM on Wednesday, June 04, 2014, the temperature is 20.6 Celsius
    
  • Ciąg formatu złożonego nie jest dobrze sformułowany. W takim przypadku FormatException wyjątek jest zawsze wynikiem błędu dewelopera. Powinna być poprawiona, a nie obsługiwana try/catch w bloku.

    Próba uwzględnienia nawiasów klamrowych literału w ciągu, jak w poniższym przykładzie, zgłosi wyjątek.

    result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
                           nOpen, nClose);
    
    let result = 
        String.Format("The text has {0} '{' characters and {1} '}' characters.", nOpen, nClose)
    
    result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
                           nOpen, nClose)
    

    Zalecaną techniką dołączania nawiasów klamrowych literału w ciągu formatu złożonego jest dołączenie ich do listy obiektów i użycie elementów formatu w celu wstawienia ich do ciągu wynikowego. Można na przykład zmodyfikować poprzedni ciąg formatu złożonego, jak pokazano tutaj.

    string result;
    int nOpen = 1;
    int nClose = 2;
    result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
                           nOpen, nClose);
    Console.WriteLine(result);
    
    let result =
        String.Format("The text has {0} '{{' characters and {1} '}}' characters.", nOpen, nClose)
    
    result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
                           nOpen, nClose)
    

    Wyjątek jest również zgłaszany, jeśli ciąg formatu zawiera literówkę. Poniższe wywołanie metody String.Format pomija zamykający nawias klamrowy i paruje nawias klamrowy otwierający z nawiasem zamykającym.

    int n1 = 10;
    int n2 = 20;
    String result = String.Format("{0 + {1] = {2}",
                                  n1, n2, n1 + n2);
    
    let n1 = 10
    let n2 = 20
    String result = String.Format("{0 + {1] = {2}",
                                n1, n2, n1 + n2)
    
    Dim n1 As Integer = 10
    Dim n2 As Integer = 20
    Dim result As String = String.Format("{0 + {1] = {2}", 
                                         n1, n2, n1 + n2)
    

    Aby naprawić błąd, upewnij się, że wszystkie nawiasy klamrowe otwierające i zamykające odpowiadają.

    String result = String.Format("{0} + {1} = {2}",
                                  n1, n2, n1 + n2);
    
    let result = String.Format("{0} + {1} = {2}", n1, n2, n1 + n2)
    
    Dim result As String = String.Format("{0} + {1} = {2}", 
                                         n1, n2, n1 + n2)
    
  • Lista obiektów została dostarczona w metodzie formatowania złożonego jako silnie typizowanej tablicy parametrów, a FormatException wyjątek wskazuje, że indeks co najmniej jednego elementu formatu przekracza liczbę argumentów na liście obiektów. Dzieje się tak, ponieważ nie istnieje jawna konwersja między typami tablicy, więc zamiast tego kompilator traktuje tablicę jako pojedynczy argument, a nie jako tablicę parametrów. Na przykład następujące wywołanie Console.WriteLine(String, Object[]) metody zgłasza FormatException wyjątek, chociaż najwyższy indeks elementów formatu wynosi 3, a tablica parametrów typu Int32 ma cztery elementy.

    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()
    
    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@()
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim numbers(3) As Integer
          Dim total As Integer = 0
          For ctr = 0 To 2
             Dim number As Integer = rnd.Next(1001)
             numbers(ctr) = number
             total += number
          Next
          numbers(3) = total
          Console.WriteLine("{0} + {1} + {2} = {3}", numbers)   
       End Sub
    End Module
    ' 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()
    

    Zamiast obsługiwać ten wyjątek, należy wyeliminować jego przyczynę. Ponieważ ani Visual Basic, ani C# nie mogą przekonwertować tablicy całkowitej na tablicę obiektów, należy wykonać konwersję samodzielnie przed wywołaniem metody formatowania złożonego. Poniższy przykład zawiera jedną implementację.

    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
    
    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
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim numbers(3) As Integer
          Dim total As Integer = 0
          For ctr = 0 To 2
             Dim number As Integer = rnd.Next(1001)
             numbers(ctr) = number
             total += number
          Next
          numbers(3) = total
          Dim values(numbers.Length - 1) As Object
          numbers.CopyTo(values, 0) 
          Console.WriteLine("{0} + {1} + {2} = {3}", values)   
       End Sub
    End Module
    ' The example displays output like the following:
    '       477 + 956 + 901 = 2334
    

FormatException używa COR_E_FORMAT HRESULT, który ma wartość 0x80131537.

Klasa FormatException pochodzi z Exception klasy i nie dodaje żadnych unikatowych elementów członkowskich. Aby uzyskać listę początkowych wartości właściwości dla wystąpienia programu FormatException, zobacz FormatException konstruktory.

Konstruktory

FormatException()

Inicjuje nowe wystąpienie klasy FormatException.

FormatException(SerializationInfo, StreamingContext)

Inicjuje nowe wystąpienie klasy FormatException z zserializowanymi danymi.

FormatException(String)

Inicjuje FormatException nowe wystąpienie klasy z określonym komunikatem o błędzie.

FormatException(String, Exception)

Inicjuje nowe wystąpienie FormatException klasy z określonym komunikatem o błędzie i odwołaniem do wewnętrznego wyjątku, który jest przyczyną tego wyjątku.

Właściwości

Data

Pobiera kolekcję par klucz/wartość, które zapewniają dodatkowe informacje zdefiniowane przez użytkownika dotyczące wyjątku.

(Odziedziczone po Exception)
HelpLink

Pobiera lub ustawia link do pliku pomocy skojarzonego z tym wyjątkiem.

(Odziedziczone po Exception)
HResult

Pobiera lub ustawia HRESULT, zakodowaną wartość liczbową przypisaną do określonego wyjątku.

(Odziedziczone po Exception)
InnerException

Exception Pobiera wystąpienie, które spowodowało bieżący wyjątek.

(Odziedziczone po Exception)
Message

Pobiera komunikat opisujący bieżący wyjątek.

(Odziedziczone po Exception)
Source

Pobiera lub ustawia nazwę aplikacji lub obiektu, który powoduje błąd.

(Odziedziczone po Exception)
StackTrace

Pobiera reprezentację ciągu natychmiastowych ramek w stosie wywołań.

(Odziedziczone po Exception)
TargetSite

Pobiera metodę, która zgłasza bieżący wyjątek.

(Odziedziczone po Exception)

Metody

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetBaseException()

Po przesłonięciu w klasie pochodnej funkcja zwraca Exception główną przyczynę co najmniej jednego kolejnego wyjątku.

(Odziedziczone po Exception)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetObjectData(SerializationInfo, StreamingContext)

Po zastąpieniu w klasie pochodnej ustawia SerializationInfo element z informacjami o wyjątku.

(Odziedziczone po Exception)
GetType()

Pobiera typ środowiska uruchomieniowego bieżącego wystąpienia.

(Odziedziczone po Exception)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Tworzy i zwraca reprezentację ciągu bieżącego wyjątku.

(Odziedziczone po Exception)

Zdarzenia

SerializeObjectState
Nieaktualne.

Występuje, gdy wyjątek jest serializowany w celu utworzenia obiektu stanu wyjątku zawierającego serializowane dane o wyjątku.

(Odziedziczone po Exception)

Dotyczy

Zobacz też