Skip to content
AgileLogics
4 min read

Exceptions

Prerequisites: Basic error handling

Beyond catching built-in errors, you can define and throw your own to signal a specific problem clearly.

class InsufficientFundsError extends Error {}

function withdraw(balance, amount) {
    if (amount > balance) {
        throw new InsufficientFundsError("Not enough balance");
    }
    return balance - amount;
}

try {
    withdraw(100, 150);
} catch (error) {
    console.log(`Withdrawal failed: ${error.message}`);
} finally {
    console.log("Transaction attempt finished");
}

Expected output

Withdrawal failed: Not enough balance
Transaction attempt finished

finally runs whether or not an error happened — useful for cleanup that must always occur.