FormatException in C#: What It Is and How to Use It
FormatException in C# is an error that happens when a string is not in the correct format expected by a method, like when converting text to numbers. It signals that the input cannot be understood or parsed properly.How It Works
Imagine you have a form where you ask someone to enter their age as a number. If they type letters instead of digits, the program won’t understand it and will raise a FormatException. This exception tells the program that the input string does not match the expected format.
In C#, many methods try to convert strings into other types like numbers or dates. When the string is not shaped correctly—like "abc" instead of "123"—the method throws a FormatException. It acts like a safety net to catch wrong inputs early and prevent the program from continuing with bad data.
Example
This example shows how FormatException occurs when trying to convert a non-numeric string to an integer.
using System; class Program { static void Main() { string input = "hello"; try { int number = int.Parse(input); Console.WriteLine($"Number is {number}"); } catch (FormatException ex) { Console.WriteLine("Caught a FormatException: The input is not a valid number."); } } }
When to Use
You encounter FormatException mainly when converting strings to other data types like numbers, dates, or enums. Use it to catch errors when user input or external data is not in the expected format.
For example, if you build a calculator app or a form that asks for dates, you should handle FormatException to show friendly messages or ask the user to correct their input instead of crashing the program.
Key Points
- FormatException happens when string input is not in the correct format for conversion.
- It is commonly thrown by methods like
int.Parse,DateTime.Parse, and others. - Use try-catch blocks to handle this exception and provide user-friendly feedback.
- Helps keep programs stable by preventing invalid data from causing errors later.