FormatException Classe

Definizione

Eccezione generata quando il formato di un argomento non è valido oppure quando una stringa di formato composita non è corretta.

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
Ereditarietà
FormatException
Ereditarietà
FormatException
Derivato
Attributi

Commenti

È possibile generare un'eccezione FormatException per uno dei motivi seguenti:

  • In una chiamata a un metodo che converte una stringa in un altro tipo di dati, la stringa non è conforme al modello richiesto. Ciò si verifica in genere quando si chiamano alcuni metodi della Convert classe e dei Parse metodi e ParseExact di alcuni tipi.

    Nella maggior parte dei casi, in particolare se la stringa che si sta convertendo è input da un utente o da un file di lettura, è consigliabile usare un try/catch blocco (try/with in F#) e gestire l'eccezione FormatException se la conversione non riesce. È anche possibile sostituire la chiamata al metodo di conversione con una chiamata a un TryParse metodo o TryParseExact , se presente. Tuttavia, un'eccezione FormatException generata quando si tenta di analizzare una stringa predefinita o hardcoded indica un errore del programma. In questo caso, è necessario correggere l'errore anziché gestire l'eccezione.

    La conversione di una stringa nei tipi seguenti nello System spazio dei nomi può generare un'eccezione FormatException :

    • Boolean. I Boolean.Parse(String) metodi e Convert.ToBoolean(String) richiedono che la stringa venga convertita in "True", "true", "False" o "false". Qualsiasi altro valore genera un'eccezione FormatException .

    • DateTime e DateTimeOffset. Tutti i dati di data e ora vengono interpretati in base alle convenzioni di formattazione di una determinata cultura: le impostazioni cultura correnti (o, in alcuni casi, le impostazioni cultura di dominio dell'applicazione correnti), le impostazioni cultura invarianti o le impostazioni cultura specificate. Quando si chiamano i DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) metodi e, i dati di data e DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) ora devono essere conformi esattamente a un modello specificato da una o più stringhe di formato standard o stringhe di formato personalizzate fornite come argomenti nella chiamata al metodo. Se non è conforme a un modello specifico delle impostazioni cultura previsto, viene generata un'eccezione FormatException . Ciò significa che i dati di data e ora salvati in un formato specifico delle impostazioni cultura in un sistema potrebbero non analizzare correttamente in un altro sistema.

      Per altre informazioni sull'analisi di date e ore, vedere Analisi di stringhe di data e ora e della documentazione per il metodo che ha generato l'eccezione.

    • GUID. La rappresentazione di stringa di un GUID deve essere costituita da 32 cifre esadecimali (0-F) e deve trovarsi in uno dei cinque formati di output del Guid.ToString metodo. Per altre informazioni, vedere il metodo Guid.Parse.

    • Tipi numerici, inclusi tutti gli interi firmati, gli interi senza segno e i tipi a virgola mobile. La stringa da analizzare deve essere costituita dalle cifre latine 0-9. Un segno positivo o negativo, separatore decimale, separatori di gruppo e simbolo di valuta può essere consentito anche. Il tentativo di analizzare una stringa contenente qualsiasi altro carattere genera sempre un'eccezione FormatException .

      Tutte le stringhe numeriche vengono interpretate in base alle convenzioni di formattazione di una determinata cultura: le impostazioni cultura correnti, le impostazioni cultura invarianti o le impostazioni cultura specificate. Di conseguenza, una stringa numerica analizzata usando le convenzioni di una cultura potrebbe non riuscire quando si usano le convenzioni di un'altra.

      Per altre informazioni sull'analisi delle stringhe numeriche, vedere Analisi di stringhe numeriche e la documentazione per il metodo specifico che ha generato l'eccezione.

    • Intervalli di tempo. La stringa da analizzare deve essere in formato non sensibile alle impostazioni cultura fisse o in un formato con distinzione tra impostazioni cultura definite dalle impostazioni cultura correnti, le impostazioni cultura invarianti o le impostazioni cultura specificate. Se la stringa non è in un formato appropriato o se, al minimo, i componenti giorni, ore e minuti dell'intervallo di tempo non sono presenti, il metodo di analisi genera un'eccezione FormatException . Per altre informazioni, vedere la documentazione del metodo di analisi che ha generato l'eccezione TimeSpan .

  • Un tipo implementa l'interfaccia IFormattable , che supporta stringhe di formato che definiscono la modalità di conversione di un oggetto nella relativa rappresentazione stringa e viene usata una stringa di formato non valida. Questa operazione è più comune in un'operazione di formattazione. Nell'esempio seguente viene usata la stringa di formato standard "Q" in una stringa di formato composito per formattare un numero. Tuttavia, "Q" non è una stringa di formato standard valida.

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

    Questa eccezione genera un errore di codifica. Per correggere l'errore, rimuovere la stringa di formato o sostituire una valida. Nell'esempio seguente viene corretto l'errore sostituendo la stringa di formato non valida con la stringa di formato "C" (valuta).

    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.
    

    Un'eccezione FormatException può essere generata anche dai metodi di analisi, ad esempio DateTime.ParseExact e Guid.ParseExact, che richiedono che la stringa venga analizzata per essere conforme esattamente al modello specificato da una stringa di formato. Nell'esempio seguente la rappresentazione stringa di un GUID è prevista conforme al modello specificato dalla stringa di formato standard "G". Tuttavia, l'implementazione della struttura di non supporta la Guid stringa di IFormattable formato "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()
    

    Questa eccezione comporta anche un errore di codifica. Per correggerlo, chiamare un metodo di analisi che non richiede un formato preciso, ad esempio DateTime.Parse o Guid.Parse, o sostituire una stringa di formato valida. Nell'esempio seguente viene corretto l'errore chiamando il Guid.Parse metodo .

    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
    
  • Uno o più degli indici degli elementi di formato in una stringa di formato composito sono maggiori degli indici degli elementi dell'elenco di oggetti o della matrice di parametri. Nell'esempio seguente l'indice più grande di un elemento di formato nella stringa di formato è 3. Poiché gli indici degli elementi nell'elenco di oggetti sono basati su zero, questa stringa di formato richiederà che l'elenco degli oggetti disponga di quattro elementi. Invece, ha solo tre, , dat``tempe scale, quindi il codice genera un'eccezione FormatException in fase di esecuzione:.

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

    In questo caso, l'eccezione è un risultato dell'errore FormatException per sviluppatori. Deve essere corretto anziché gestito in un try/catch blocco assicurandosi che ogni elemento nell'elenco di oggetti corrisponda all'indice di un elemento di formato. Per correggere questo esempio, modificare l'indice del secondo elemento di formato per fare riferimento alla dat variabile e decrerere l'indice di ogni elemento di formato successivo per uno.

    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
    
  • La stringa di formato composito non è ben formata. In questo caso, l'eccezione è sempre un risultato dell'errore FormatException sviluppatore. Deve essere corretto anziché gestito in un try/catch blocco.

    Il tentativo di includere parentesi graffe letterali in una stringa, come illustrato nell'esempio seguente, genererà l'eccezione.

    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)
    

    La tecnica consigliata per includere parentesi graffe letterali in una stringa di formato composito consiste nell'includerle nell'elenco di oggetti e usare gli elementi di formato per inserirli nella stringa di risultato. Ad esempio, è possibile modificare la stringa di formato composito precedente, come illustrato qui.

    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)
    

    L'eccezione viene generata anche se la stringa di formato contiene un errore di digitatura. La chiamata seguente al String.Format metodo omette una parentesi graffe di chiusura e associa una parentesi graffe di apertura con una parentesi quadre di chiusura.

    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)
    

    Per correggere l'errore, assicurarsi che tutte le parentesi graffe di apertura e chiusura corrispondano.

    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)
    
  • È stato fornito l'elenco di oggetti in un metodo di formattazione composito come matrice di parametri fortemente tipizzata e l'eccezione FormatException indica che l'indice di uno o più elementi di formato supera il numero di argomenti nell'elenco di oggetti. Ciò si verifica perché non esiste alcuna conversione esplicita tra tipi di matrice, pertanto il compilatore considera la matrice come un singolo argomento anziché come matrice di parametri. Ad esempio, la chiamata seguente al Console.WriteLine(String, Object[]) metodo genera un'eccezione FormatException , anche se l'indice più alto degli elementi di formato è 3 e la matrice di parametri di tipo Int32 ha quattro elementi.

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

    Anziché gestire questa eccezione, è necessario eliminare la causa. Poiché né Visual Basic né C# possono convertire una matrice integer in una matrice di oggetti, è necessario eseguire la conversione manualmente prima di chiamare il metodo di formattazione composito. Nell'esempio seguente viene fornita un'implementazione.

    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 usa il COR_E_FORMAT HRESULT, che ha il valore 0x80131537.

La FormatException classe deriva da Exception e non aggiunge membri univoci. Per un elenco di valori di proprietà iniziali per un'istanza di FormatException, vedere il FormatException costruttori.

Costruttori

FormatException()

Inizializza una nuova istanza della classe FormatException.

FormatException(SerializationInfo, StreamingContext)

Inizializza una nuova istanza della classe FormatException con dati serializzati.

FormatException(String)

Inizializza una nuova istanza della classe FormatException con un messaggio di errore specificato.

FormatException(String, Exception)

Inizializza una nuova istanza della classe FormatException con un messaggio di errore specificato e un riferimento all'eccezione interna che è la causa dell'eccezione corrente.

Proprietà

Data

Ottiene una raccolta di coppie chiave/valore che forniscono informazioni definite dall'utente aggiuntive sull'eccezione.

(Ereditato da Exception)
HelpLink

Ottiene o imposta un collegamento al file della Guida associato all'eccezione.

(Ereditato da Exception)
HResult

Ottiene o imposta HRESULT, un valore numerico codificato che viene assegnato a un'eccezione specifica.

(Ereditato da Exception)
InnerException

Ottiene l'istanza di Exception che ha causato l'eccezione corrente.

(Ereditato da Exception)
Message

Ottiene un messaggio che descrive l'eccezione corrente.

(Ereditato da Exception)
Source

Ottiene o imposta il nome dell'oggetto o dell'applicazione che ha generato l'errore.

(Ereditato da Exception)
StackTrace

Ottiene una rappresentazione di stringa dei frame immediati nello stack di chiamate.

(Ereditato da Exception)
TargetSite

Ottiene il metodo che genera l'eccezione corrente.

(Ereditato da Exception)

Metodi

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetBaseException()

Quando ne viene eseguito l'override in una classe derivata, restituisce l'Exception che è la causa radice di una o più eccezioni successive.

(Ereditato da Exception)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetObjectData(SerializationInfo, StreamingContext)

Quando ne viene eseguito l'override in una classe derivata, imposta il controllo SerializationInfo con le informazioni sull'eccezione.

(Ereditato da Exception)
GetType()

Ottiene il tipo di runtime dell'istanza corrente.

(Ereditato da Exception)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
ToString()

Crea e restituisce una rappresentazione di stringa dell'eccezione corrente.

(Ereditato da Exception)

Eventi

SerializeObjectState
Obsoleta.

Si verifica quando un'eccezione viene serializzata per creare un oggetto di stato eccezione contenente i dati serializzati relativi all'eccezione.

(Ereditato da Exception)

Si applica a

Vedi anche