Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

FormatException

Reference for FormatException in C#: why int.Parse, DateTime.Parse and string.Format fail, how TryParse avoids exceptions, and culture-safe parsing.

FormatException is thrown when text is not in the format a method expects. The most common cause is parsing: int.Parse("12x"), double.Parse(""), Guid.Parse("nope"), DateTime.Parse("tomorrow"). It is also thrown for broken composite format strings, for example string.Format("{0} {1}", "only one"), where an index refers to an argument that was not supplied.

When bad input is expected, as it is for anything typed by users or read from files, use the TryParse methods. They return false instead of throwing, which is faster and keeps the normal flow clear. Overflow is a separate case: int.Parse("99999999999") is well-formed text, but the number is too big, so it throws OverflowException.

C#
if (int.TryParse(input, out int value)) { Console.WriteLine(value * 2); }

Try it

C# Parse versus TryParse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Culture, number styles and format strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public class FormatException : SystemException
{
    public FormatException();
    public FormatException(string? message);
    public FormatException(string? message, Exception? innerException);
}

static int Parse(string s)                                  // throws FormatException, OverflowException
static bool TryParse(string? s, out int result)             // never throws for bad text
static bool TryParse(string? s, IFormatProvider? provider, out int result)
Name Description
s Text to convert. Parse(null) throws ArgumentNullException; TryParse(null) returns false.
provider Supplies culture rules such as the decimal separator. Pass CultureInfo.InvariantCulture for machine-readable text.
style NumberStyles or DateTimeStyles that allow signs, spaces, thousands separators and so on.
Returns Parse returns the value. TryParse returns true on success and sets result; on failure result is 0/default.

Usage notes

  • Use TryParse for input you do not control. Exceptions are slow and make normal validation look like error handling.
  • Whitespace. Leading and trailing spaces are allowed for numbers by default; inner spaces are not.
  • Culture matters. The same text parses differently with a comma-decimal culture. Our runner uses the invariant culture, so de-DE style parsing cannot be demonstrated live; always pass an explicit provider in libraries.
  • Empty and null. An empty string is a FormatException for Parse; null is an ArgumentNullException.
  • Format versus range. Text that is syntactically a number but too large gives OverflowException, not FormatException.
  • Other sources: Convert.ToInt32(string), Enum.Parse, Guid.Parse, Version.Parse, Convert.FromBase64String and composite formatting can all throw FormatException (Enum.Parse throws ArgumentException for unknown names).
  • Parsing spans. int.TryParse(ReadOnlySpan<char>, out int) avoids allocating substrings.
  • Generic parsing. Number types implement IParsable<T> so T.Parse and T.TryParse work in generic code.