try–catch–finally
Use try
for code that might throw. Handle failures in catch (err)
.
Use finally
for cleanup that must run whether success or failure.
Throw errors with throw
to signal exceptional conditions.
Syntax
try {
// risky work
} catch (err) {
// handle
} finally {
// cleanup (always runs)
}
// You can omit catch, but then finally must be present
try {
// ...
} finally {
// cleanup
}
// Throwing
throw new Error("message");
Examples
// ১) JSON পার্সিং
চেষ্টা {
const ডেটা = '{"name":"Bnlang"}';
const obj = JSON.parse(ডেটা);
কনসোল.লগ("নাম:", obj.name);
} ধরুন (ত্রু) {
কনসোল.ত্রুটি("পার্সিং ব্যর্থ:", ত্রু.message);
} অবশেষে {
কনসোল.তথ্য("পার্সের চেষ্টা শেষ");
}
// ২) ইনপুট যাচাই + rethrow
function ব্যবহারকারী_লোড(আইডি) {
চেষ্টা {
যদি (আইডি == null) নিক্ষেপ new Error("আইডি লাগবে");
// ... ডাটাবেস থেকে পড়া
ফেরত { id: আইডি, নাম: "Mamun" };
} ধরুন (ত্রু) {
কনসোল.ত্রুটি("লোড ব্যর্থ:", ত্রু.message);
নিক্ষেপ ত্রু; // মূল ত্রুটি আবার ছুঁড়ে দিচ্ছি
} অবশেষে {
কনসোল.লগ("রিসোর্স মুক্ত");
}
}
// ৩) return থাকলেও অবশেষে চলবে
function ভাগ(a, b) {
চেষ্টা {
যদি (b === 0) নিক্ষেপ new Error("শূন্য দ্বারা ভাগ নয়");
ফেরত a / b;
} ধরুন (ত্রু) {
ফেরত NaN;
} অবশেষে {
কনসোল.তথ্য("ভাগ শেষ");
}
}
// ৪) অপেক্ষা/অসমলয় সহ
অসমলয় function ডাউনলোড(url) {
চেষ্টা {
const res = অপেক্ষা fetch(url);
যদি (!res.ok) নিক্ষেপ new Error("রেসপন্স ব্যর্থ");
ফেরত অপেক্ষা res.text();
} ধরুন (ত্রু) {
কনসোল.ত্রুটি("ডাউনলোড ব্যর্থ:", ত্রু.message);
ফেরত null;
} অবশেষে {
কনসোল.লগ("নেটওয়ার্ক ক্লিন‑আপ");
}
}
Notes
try
may be paired with eithercatch
orfinally
(or both), but not neither.- The
finally
block runs even if there is areturn
,break
,continue
, orthrow
insidetry
/catch
. - Prefer rethrowing the same error object (
throw err
) to preserve the original stack. - For async code,
try/catch
works withawait
; for bare Promises, use.catch(...)
. - Avoid swallowing errors silently; log and rethrow when appropriate.