Exception: try/catch/finally
Tangkap error tanpa crash + throw dan custom Error.
Pahami konsepnya
JavaScript menangani error lewat exception: kode yang melempar Error menghentikan eksekusi sampai ditangkap try/catch. try membungkus kode berisiko; catch menangkap Error object (punya .message dan .name); finally berjalan SELALU — cocok untuk cleanup.
Tipe error: TypeError (akses properti null), ReferenceError (variabel tidak ada), SyntaxError (kode salah tulis), RangeError (nilai di luar rentang). Catch bisa memfilter: catch (e) { if (e instanceof TypeError) ... }.
throw melempar error sendiri: throw new Error("harga tidak boleh negatif"). Custom error: class ValidationError extends Error — menambah tipe spesifik untuk ditangkap berbeda.
Coba contoh kode
function bagi(a, b) {
if (b === 0) throw new Error("Pembagi tidak boleh nol");
return a / b;
}
try {
console.log(bagi(10, 2));
console.log(bagi(10, 0));
} catch (e) {
console.log(`Gagal: ${e.message}`);
} finally {
console.log("Selalu berjalan.");
}
// custom error
class ValidationError extends Error {
constructor(nama) {
super(`${nama} tidak valid`);
this.name = "ValidationError";
}
}
try { throw new ValidationError("harga"); }
catch (e) { console.log(e.name, e.message); }Fungsi bagi melempar Error saat pembagi nol; catch menangkap dan menampilkan message. finally berjalan baik sukses maupun gagal. Custom error ValidationError menambah name spesifik untuk pembedaan.
Latihan singkat
Uji: throw new Error("test") → catch → cetak `test`.