Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

FormatException ใน C#


ภาพรวม

FormatException เป็นข้อยกเว้นที่โยนเมื่อ รูปแบบของอาร์กิวเมนต์ไม่ถูกต้อง เช่น พยายามแปลงสตริงที่ไม่ใช่ตัวเลขให้เป็นตัวเลข

ตัวอย่างที่ทำให้เกิด FormatException

using System;

class Demo
{
    static void Main()
    {
        string str = "3.5"; // มีจุดทศนิยม ไม่ใช่ int
        int res = int.Parse(str); // โยน FormatException
    }
}

ข้อความข้อผิดพลาด

Unhandled Exception: System.FormatException: Input string was not in a correct format.

วิธีแก้ไขและป้องกัน

  • ใช้ int.TryParse() แทน int.Parse() เพื่อตรวจสอบก่อนแปลง
  • ตรวจสอบรูปแบบข้อมูลก่อนแปลง (เช่น Regex, ตรวจสอบ IsNumeric)
  • ใช้ Convert.ToInt32() ซึ่งจัดการ null ได้ดีกว่า (คืน 0)
  • จับข้อยกเว้นด้วย try-catch เพื่อให้โปรแกรมไม่หยุดทำงาน

ตัวอย่างการใช้ TryParse

string input = "3.5";
if (int.TryParse(input, out int result))
{
    Console.WriteLine("แปลงสำเร็จ: " + result);
}
else
{
    Console.WriteLine("รูปแบบไม่ถูกต้อง");
}