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

OverflowException ใน C#


ภาพรวม

OverflowException โยนเมื่อ ค่าพารามิเตอร์อยู่นอกขอบเขตของชนิดข้อมูล เช่น พยายามแปลงสตริงที่มีค่ามากเกินไปให้เป็น int

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

using System;

class Demo
{
    static void Main()
    {
        string str = "757657657657657"; // มากกว่า Int32.MaxValue
        int res = int.Parse(str); // โยน OverflowException
    }
}

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

Unhandled Exception: System.OverflowException: Value was either too large or too small for an Int32.

ขอบเขตของชนิดข้อมูลจำนวนเต็มหลัก

ชนิดขอบเขต
sbyte-128 ถึง 127
byte0 ถึง 255
short (Int16)-32,768 ถึง 32,767
ushort (UInt16)0 ถึง 65,535
int (Int32)-2,147,483,648 ถึง 2,147,483,647
uint (UInt32)0 ถึง 4,294,967,295
long (Int64)-9,223,372,036,854,775,808 ถึง 9,223,372,036,854,775,807

วิธีป้องกัน

  • ใช้ TryParse ตรวจสอบก่อนแปลง
  • ใช้ checked / unchecked บล็อกควบคุมการตรวจสอบล้น
  • เลือกชนิดข้อมูลที่มีขอบเขตเพียงพอ (เช่น long แทน int)