FormatException तब फेंका जाता है जब किसी आर्गुमेंट का फॉर्मेट अमान्य होता है (जैसे गैर-संख्यात्मक स्ट्रिंग को int.Parse में पास करना)।
उदाहरण
using System;
class Demo
{
static void Main()
{
string str = "3.5";
int res = int.Parse(str); // ❌ FormatException: "3.5" इंट नहीं
}
}
आउटपुट
Unhandled Exception: System.FormatException: Input string was not in a correct format.
सामान्य कारण
int.Parse("abc"),double.Parse("xyz")।DateTime.Parse("invalid-date")।Guid.Parse("not-a-guid")।- कंपोजिट फॉर्मेटिंग में गलत प्लेसहोल्डर:
string.Format("{0}{1}", val)(दूसरा आर्गुमेंट गायब)।
हैंडलिंग
// 1. TryParse पैटर्न (अनुशंसित)
if (int.TryParse(str, out int result))
Console.WriteLine(result);
else
Console.WriteLine("अमान्य संख्या");
// 2. Try-Catch
try { int x = int.Parse(str); }
catch (FormatException) { /* हैंडल */ }
// 3. वैलिडेशन पहले
if (int.TryParse(str, out _)) { ... }