Skip to content
คำสั่งการใช้งาน
tryตรวจสอบ error
catchถ้า error จะทำอะไร
finallyสิ่งที่ทำเสมอไม่ว่าจะ error หรือไม่ก็ตาม
throwแสดง error

try-catch-finally-throw

js
async function withdrawFromATM(amount) {
    const accountBalance = 1000;
    let transactionStatus = "Failed";

    try {
        console.log("Checking account balance...");

        // ตรวจสอบค่าที่ไม่ใช่ number
        if (typeof amount !== 'number') {
            throw new Error("Please enter the amount as a number");
        }

        // ตรวจสอบจำนวนเงินที่ถอน
        if (amount <= 0) {
            throw new Error("Withdrawal amount must be greater than 0");
        }

        // ตรวจสอบยอดเงินในบัญชี
        if (amount > accountBalance) {
            throw new Error("Insufficient funds in the account");
        }

        // จำลองการถอนเงินด้วย Promise
        await new Promise((resolve, reject) => {
            console.log(`Withdrawing ${amount} dollars...`);
            setTimeout(() => {
                resolve(); // จำลองการถอนเงินที่ใช้เวลา 1 วินาที
            }, 1000);
        });

        // หากทุกการตรวจสอบผ่าน
        transactionStatus = "Successful";
        console.log("Withdrawal successful");

    } catch (error) {
        // แสดงข้อความข้อผิดพลาดในคอนโซล
        console.error("Error occurred:", error.message);
    } finally {
        // ข้อความที่จะแสดงเสมอ
        console.log("Printing receipt...");
        console.log(`Transaction status: ${transactionStatus}`);
        console.log("Don't forget to take your card");
    }
}

// เรียกใช้ฟังก์ชันแบบอะซิงโครนัส
withdrawFromATM(500);  // ลองเปลี่ยนเป็น -500 หรือ 1500 เพื่อทดสอบการจัดการข้อผิดพลาด

try

catch

finally

throw

Released under the MIT License