FormatException
Summary
Represents errors that occur when the format of a string or other input data is not valid.
Syntax
public class FormatException : Exception
Namespace: System
Assembly: System.Runtime.dll
Remarks
The FormatException
class is used to signal that an input string does not conform to the expected format. For example, this exception can be thrown when parsing a string to a numeric type (like int.Parse
or double.Parse
) and the string contains invalid characters or an incorrect structure.
This exception is typically thrown by methods that convert a string representation of a value to its equivalent numeric, date and time, or other non-string type.
The FormatException
class inherits from the Exception
class. It includes standard exception properties such as Message
, InnerException
, and StackTrace
.
Exceptions
- FormatException: The input string is not in a recognized format.
Example
The following code example demonstrates how to catch a FormatException
when attempting to parse an invalid string to an integer.
using System;
public class Example
{
public static void Main(string[] args)
{
string invalidString = "abc";
int number;
try
{
number = int.Parse(invalidString);
Console.WriteLine($"Parsed number: {number}");
}
catch (FormatException e)
{
Console.WriteLine($"Error: {e.Message}");
Console.WriteLine("The input string is not a valid integer format.");
}
catch (OverflowException e)
{
Console.WriteLine($"Error: {e.Message}");
Console.WriteLine("The number is too large or too small for an Int32.");
}
}
}