Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
FormatException in C#
A FormatException is thrown when the format of an argument is invalid or cannot be converted to the expected data type. This commonly occurs when attempting to parse a string that doesn't match the expected format for numeric or date types.
Common Scenarios
FormatException typically occurs in these situations −
-
Parsing a non-numeric string as a number using
int.Parse(),double.Parse(), etc. -
Converting a string with decimal points to an integer
-
Parsing invalid date formats using
DateTime.Parse() -
Using incorrect format specifiers in string formatting
Using int.Parse() with Invalid Format
When we pass a value that cannot be converted to an integer to the int.Parse() method, a FormatException is thrown −
using System;
class Demo {
static void Main() {
try {
string str = "3.5";
int res = int.Parse(str);
Console.WriteLine("Parsed value: " + res);
}
catch (FormatException ex) {
Console.WriteLine("FormatException caught: " + ex.Message);
}
}
}
The output of the above code is −
FormatException caught: Input string was not in a correct format.
Using DateTime.Parse() with Invalid Format
FormatException also occurs when parsing invalid date strings −
using System;
class Demo {
static void Main() {
try {
string dateStr = "invalid-date";
DateTime date = DateTime.Parse(dateStr);
Console.WriteLine("Parsed date: " + date);
}
catch (FormatException ex) {
Console.WriteLine("FormatException caught: " + ex.Message);
}
}
}
The output of the above code is −
FormatException caught: String was not recognized as a valid DateTime.
Preventing FormatException
Use TryParse() methods to safely convert strings without throwing exceptions −
using System;
class Demo {
static void Main() {
string str1 = "123";
string str2 = "3.5";
if (int.TryParse(str1, out int result1)) {
Console.WriteLine("Successfully parsed: " + result1);
} else {
Console.WriteLine("Failed to parse: " + str1);
}
if (int.TryParse(str2, out int result2)) {
Console.WriteLine("Successfully parsed: " + result2);
} else {
Console.WriteLine("Failed to parse: " + str2);
}
}
}
The output of the above code is −
Successfully parsed: 123 Failed to parse: 3.5
Conclusion
FormatException occurs when attempting to convert or parse data with an invalid format. Use try-catch blocks to handle these exceptions gracefully, or prefer TryParse() methods to avoid exceptions when the input format might be invalid.
