FormatException 클래스

정의

인수의 형식이 올바르지 않거나 합성 서식 문자열이 잘못 만들어진 경우 예외가 throw됩니다.

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
상속
FormatException
상속
FormatException
파생
특성

설명

FormatException 다음 이유 중 하나로 예외가 throw될 수 있습니다.

  • 문자열을 다른 데이터 형식으로 변환하는 메서드 호출에서 문자열은 필요한 패턴을 따르지 않습니다. 이는 일반적으로 클래스의 일부 메서드 및 일부 형식의 Convert 메서드를 ParseExact 호출할 Parse 때 발생합니다.

    대부분의 경우, 특히 변환하는 문자열이 사용자의 입력이거나 파일에서 읽는 경우 변환에 실패한 경우 (try/withF#) 블록을 사용하고 try/catch 예외를 FormatException 처리해야 합니다. 변환 메서드 호출이 있는 경우 변환 메서드 호출을 a TryParse 또는 TryParseExact 메서드 호출로 바꿀 수도 있습니다. 그러나 FormatException 미리 정의되거나 하드 코드된 문자열을 구문 분석하려고 할 때 throw되는 예외는 프로그램 오류를 나타냅니다. 이 경우 예외를 처리하는 대신 오류를 수정해야 합니다.

    네임스페이스에서 문자열을 다음 형식으로 변환하면 System 예외가 throw됩니다.FormatException

    • Boolean. 및 Convert.ToBoolean(String) 메서드를 Boolean.Parse(String) 사용하려면 문자열을 "True", "true", "False" 또는 "false"로 변환해야 합니다. 다른 값은 예외를 FormatException throw합니다.

    • DateTimeDateTimeOffset을 참조하세요. 모든 날짜 및 시간 데이터는 현재 문화권(또는 경우에 따라 현재 애플리케이션 도메인 문화권), 고정 문화권 또는 지정된 문화권과 같은 특정 문화권의 서식 규칙에 따라 해석됩니다. 및 DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 메서드를 DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) 호출할 때 날짜 및 시간 데이터도 메서드 호출에서 인수로 제공되는 하나 이상의 표준 형식 문자열 또는 사용자 지정 형식 문자열로 지정된 패턴을 정확히 준수해야 합니다. 예상되는 문화권별 패턴을 따르지 않으면 예외가 FormatException throw됩니다. 즉, 한 시스템에서 문화권별 형식으로 저장된 날짜 및 시간 데이터가 다른 시스템에서 성공적으로 구문 분석되지 않을 수 있습니다.

      날짜 및 시간 구문 분석에 대한 자세한 내용은 날짜 및 시간 문자열 구문 분석 및 예외를 throw한 메서드에 대한 설명서를 참조하세요.

    • GUID입니다. GUID의 문자열 표현은 326진수(0-F)로 구성되어야 하며 메서드에서 출력 Guid.ToString 하는 5가지 형식 중 하나여야 합니다. 자세한 내용은 Guid.Parse 메서드를 참조하세요.

    • 부호 있는 모든 정수, 부호 없는 정수 및 부동 소수점 형식을 포함한 숫자 형식입니다. 구문 분석할 문자열은 라틴 숫자 0-9로 구성되어야 합니다. 양수 또는 음수 기호, 소수 구분 기호, 그룹 구분 기호 및 통화 기호도 허용될 수 있습니다. 다른 문자가 포함된 문자열을 구문 분석하려고 하면 항상 예외가 FormatException throw됩니다.

      모든 숫자 문자열은 현재 문화권, 고정 문화권 또는 지정된 문화권과 같은 특정 문화권의 서식 규칙에 따라 해석됩니다. 따라서 한 문화권의 규칙을 사용하여 구문 분석되는 숫자 문자열은 다른 문화권의 규칙을 사용할 때 실패할 수 있습니다.

      숫자 문자열 구문 분석에 대한 자세한 내용은 숫자 문자열 구문 분석 및 예외를 throw한 특정 메서드에 대한 설명서를 참조하세요.

    • 시간 간격입니다. 구문 분석할 문자열은 고정 문화권을 구분하지 않는 형식이거나 현재 문화권, 고정 문화권 또는 지정된 문화권으로 정의된 문화권 구분 형식이어야 합니다. 문자열이 적절한 형식이 아니거나 최소한 시간 간격의 일, 시간 및 분 구성 요소가 없는 경우 구문 분석 메서드는 예외를 FormatException throw합니다. 자세한 내용은 예외를 throw한 TimeSpan 구문 분석 방법에 대한 설명서를 참조하세요.

  • 형식은 개체가 IFormattable 문자열 표현으로 변환되는 방법을 정의하는 형식 문자열을 지원하고 잘못된 형식 문자열을 사용하는 인터페이스를 구현합니다. 이는 서식 지정 작업에서 가장 일반적입니다. 다음 예제에서는 "Q" 표준 서식 문자열을 복합 형식 문자열에 사용하여 숫자 서식을 지정합니다. 그러나 "Q"는 유효한 표준 형식 문자열이 아닙니다.

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

    이 예외는 코딩 오류로 인해 발생합니다. 오류를 수정하려면 형식 문자열을 제거하거나 유효한 문자열을 대체합니다. 다음 예제에서는 잘못된 형식 문자열을 "C"(통화) 형식 문자열로 바꿔 오류를 수정합니다.

    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.
    

    FormatException 형식 문자열에서 지정한 패턴을 정확히 준수하도록 문자열을 구문 분석해야 하는 메서드와 Guid.ParseExact같은 DateTime.ParseExact 구문 분석 메서드를 통해 예외를 throw할 수도 있습니다. 다음 예제에서는 GUID의 문자열 표현이 "G" 표준 형식 문자열로 지정된 패턴을 준수해야 합니다. 그러나 Guid 구조체의 구현 IFormattable 은 "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()
    

    또한 이 예외는 코딩 오류로 인해 발생합니다. 이를 수정하려면 정확한 형식(예: DateTime.Parse 또는 Guid.Parse유효한 형식 문자열)이 필요하지 않은 구문 분석 메서드를 호출합니다. 다음 예제에서는 메서드를 호출하여 오류를 수정합니다 Guid.Parse .

    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
    
  • 복합 서식 문자열에 있는 서식 항목의 인덱스 중 하나 이상이 개체 목록 또는 매개 변수 배열에 있는 항목의 인덱스보다 큽니다. 다음 예제에서는 서식 문자열에서 서식 항목의 가장 큰 인덱스는 3입니다. 개체 목록에 있는 항목의 인덱스는 0부터 시작하는 형식이므로 이 형식 문자열을 사용하려면 개체 목록에 4개의 항목이 있어야 합니다. 대신, 3개, tempscale3개dat만 있으므로 코드는 런타임에 예외가 FormatException 발생합니다.

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

    이 경우 예외는 FormatException 개발자 오류의 결과입니다. 개체 목록의 각 항목이 형식 항목의 인덱스에 해당하는지 확인하여 블록에서 처리 try/catch 하지 않고 수정해야 합니다. 이 예제를 수정하려면 두 번째 서식 항목의 인덱스가 변수를 참조하도록 dat 변경하고 각 후속 형식 항목의 인덱스 수를 하나씩 감소합니다.

    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
    
  • 복합 형식 문자열의 형식이 잘못되었습니다. 이 경우 FormatException 예외는 항상 개발자 오류의 결과입니다. 블록에서 try/catch 처리하지 않고 수정해야 합니다.

    다음 예제와 같이 문자열에 리터럴 중괄호를 포함하려고 하면 예외가 throw됩니다.

    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)
    

    복합 형식 문자열에 리터럴 중괄호를 포함하는 데 권장되는 방법은 개체 목록에 리터럴 중괄호를 포함하고 서식 항목을 사용하여 결과 문자열에 삽입하는 것입니다. 예를 들어 다음과 같이 이전 복합 형식 문자열을 수정할 수 있습니다.

    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)
    

    형식 문자열에 오타가 포함된 경우에도 예외가 throw됩니다. 메서드에 String.Format 대한 다음 호출은 닫는 중괄호를 생략하고 여는 중괄호를 닫는 대괄호와 쌍을 이릅니다.

    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)
    

    오류를 수정하려면 모든 여는 중괄호와 닫는 중괄호가 해당하는지 확인합니다.

    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)
    
  • 복합 서식 지정 메서드에서 개체 목록을 강력한 형식의 매개 변수 배열로 제공했으며 FormatException , 예외는 하나 이상의 서식 항목의 인덱스가 개체 목록의 인수 수를 초과한다는 것을 나타냅니다. 이는 배열 형식 간에 명시적 변환이 없기 때문에 발생하므로 대신 컴파일러는 배열을 매개 변수 배열이 아닌 단일 인수로 처리합니다. 예를 들어 다음 메서드 호출 Console.WriteLine(String, Object[]) 은 형식 항목의 가장 높은 인덱스가 FormatException 3이고 형식 Int32 의 매개 변수 배열에 4개의 요소가 있지만 예외를 throw합니다.

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

    이 예외를 처리하는 대신 원인을 제거해야 합니다. Visual Basic 또는 C#은 정수 배열을 개체 배열로 변환할 수 없으므로 복합 서식 지정 메서드를 호출하기 전에 직접 변환을 수행해야 합니다. 다음 예제에서는 한 가지 구현을 제공합니다.

    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 는 값이 0x80131537 HRESULT COR_E_FORMAT 사용합니다.

클래스는 FormatException Exception 파생되고 고유한 멤버를 추가하지 않습니다. 인스턴스의 초기 속성 값의 목록을 FormatException, 참조는 FormatException 생성자입니다.

생성자

FormatException()

FormatException 클래스의 새 인스턴스를 초기화합니다.

FormatException(SerializationInfo, StreamingContext)

serialize된 데이터를 사용하여 FormatException 클래스의 새 인스턴스를 초기화합니다.

FormatException(String)

지정된 오류 메시지를 사용하여 FormatException 클래스의 새 인스턴스를 초기화합니다.

FormatException(String, Exception)

지정된 오류 메시지와 해당 예외의 원인인 내부 예외에 대한 참조를 사용하여 FormatException 클래스의 새 인스턴스를 초기화합니다.

속성

Data

예외에 대한 사용자 정의 정보를 추가로 제공하는 키/값 쌍 컬렉션을 가져옵니다.

(다음에서 상속됨 Exception)
HelpLink

이 예외와 연결된 도움말 파일에 대한 링크를 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
HResult

특정 예외에 할당된 코드화된 숫자 값인 HRESULT를 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
InnerException

현재 예외를 발생시킨 Exception 인스턴스를 가져옵니다.

(다음에서 상속됨 Exception)
Message

현재 예외를 설명하는 메시지를 가져옵니다.

(다음에서 상속됨 Exception)
Source

오류를 발생시키는 애플리케이션 또는 개체의 이름을 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
StackTrace

호출 스택의 직접 실행 프레임 문자열 표현을 가져옵니다.

(다음에서 상속됨 Exception)
TargetSite

현재 예외를 throw하는 메서드를 가져옵니다.

(다음에서 상속됨 Exception)

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetBaseException()

파생 클래스에서 재정의된 경우 하나 이상의 후속 예외의 근본 원인이 되는 Exception 을 반환합니다.

(다음에서 상속됨 Exception)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetObjectData(SerializationInfo, StreamingContext)

파생 클래스에서 재정의된 경우 예외에 관한 정보를 SerializationInfo 에 설정합니다.

(다음에서 상속됨 Exception)
GetType()

현재 인스턴스의 런타임 형식을 가져옵니다.

(다음에서 상속됨 Exception)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 예외에 대한 문자열 표현을 만들고 반환합니다.

(다음에서 상속됨 Exception)

이벤트

SerializeObjectState
사용되지 않습니다.

예외에 대한 serialize된 데이터가 들어 있는 예외 상태 개체가 만들어지도록 예외가 serialize될 때 발생합니다.

(다음에서 상속됨 Exception)

적용 대상

추가 정보