C# FormatException

Format illustration

How can you solve the FormatException that your C# program is throwing? The System.FormatException is thrown by methods that receive format strings and substitutions. Here, we look at one program that causes it and how you can fix it.

This C# exception article demonstrates the FormatException type.

Example

In the .NET Framework, format strings use substitution markers such as {0}, {1}, and {2}. The arguments after the format string are placed in those markers in the same order. But what happens if the format string has too many markers?

Program that throws an exception [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine("{0} {2}", "x");
    }
}

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.

Answer. The System.FormatException is thrown because the {2} substitution marker was not found in the argument list. If more arguments were provided, the program would not throw an exception. To fix the program, you could remove the substitution marker {2} or add two more arguments.

Summary

The C# programming language

Exception handling in the C# language exploits the type hierarchy to provide information about what went wrong in your program. Whenever you encounter a System.FormatException, it is worthwhile to check the substitution markers and argument lists for formatting methods.

Exception Handling
.NET