แบบฝึกหัด C#

exception ทางธุรกิจที่สร้างเอง

สร้างและดักจับ exception ที่สื่อถึงความล้มเหลวทางธุรกิจ

ทำงานอย่างไร

exception ที่มีชื่อสื่อเจตนาได้ชัดกว่า Exception ทั่วไป

ชนิดที่สร้างเองยังทำงานแบบ exception ปกติ แต่ทำให้ส่วน catch แม่นยำขึ้น

ตัวอย่าง C# ที่รันได้

C#
รันโค้ด →
Program.cs
using System;
class InsufficientStockException(string message) : Exception(message) { }
class Program
{
    static void Reserve(int available, int requested)
    {
        if (requested > available) throw new InsufficientStockException("Not enough stock");
    }
    static void Main()
    {
        try { Reserve(2, 3); }
        catch (InsufficientStockException error) { Console.WriteLine(error.Message); }
    }
}
ผลลัพธ์ที่คาดหวัง
Not enough stock

ฝึกกับดีบักเกอร์

ตั้ง breakpoint ที่การกำหนดค่าหรือเงื่อนไขสำคัญ กด Debug แล้วดูค่าตัวแปรภายในก่อนไปยังบรรทัดถัดไป

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด