throw Keyword
Use throw to signal an exceptional condition. It stops normal execution and jumps to the nearest matching catch.
Prefer throwing Error objects (or subclasses) so stack traces and metadata are preserved.
Syntax
throw expression; // usually an Error
throw new Error("Message"); // recommended
class ValidationError extends Error {}
throw new ValidationError("Bad input");
Examples
// ১) বেসিক নিক্ষেপ/ধরুন
চেষ্টা {
const বয়স = -2;
যদি (বয়স < 0) নিক্ষেপ new Error("অবৈধ বয়স");
কনসোল.লগ("ঠিক আছে");
} ধরুন (ত্রু) {
কনসোল.ত্রুটি("ভুল:", ত্রু.message);
} অবশেষে {
কনসোল.তথ্য("সবশেষে চলবে");
}
// ২) কাস্টম Error সাবক্লাস
class ইনপুটত্রুটি extends Error {
constructor(msg) {
super(msg);
this.name = "ইনপুটত্রুটি";
}
}
function মূল্যায়ন(x) {
যদি (typeof x !== "number") নিক্ষেপ new ইনপুটত্রুটি("সংখ্যা দিতে হবে");
ফেরত x * 2;
}
// ৩) cause দিয়ে কনটেক্সট চেইন করা
function পার্স(json) {
চেষ্টা {
ফেরত JSON.parse(json);
} ধরুন (মূল) {
নিক্ষেপ new Error("JSON পার্স ব্যর্থ", { cause: মূল });
}
}
চেষ্টা {
পার্স("{bad json}");
} ধরুন (ত্রু) {
কনসোল.ত্রুটি(ত্রু.message);
যদি (ত্রু.cause) কনসোল.তথ্য("মূল কারণ:", ত্রু.cause.message);
}
// ৪) অসমলয় ফাংশনে নিক্ষেপ (প্রমিস রিজেক্ট)
অসমলয় function ডাউনলোড(url) {
const res = অপেক্ষা fetch(url);
যদি (!res.ok) নিক্ষেপ new Error("রেসপন্স ব্যর্থ");
ফেরত অপেক্ষা res.text();
}
Notes
- You can throw any value, but prefer
Erroror subclasses for consistent stacks and features likecause. throwaborts the current execution path and unwinds the stack until a matchingcatch.finallyruns even if athrowhappens.- Avoid using exceptions for normal control flow; reserve them for truly exceptional situations.
- When converting errors, wrap and set
{ cause: original }to keep context, or rethrow the original (throw err) to preserve its stack.