জাভাস্ক্রিপ্টে অনেক প্রকারের স্টেটমেন্ট ব্যবহার করা যায়, যার মধ্যে অনেকগুলোই কোডের কন্ট্রোল কোথায় থেকে কোথায় যাবে (কন্ট্রোল ফ্লো) তা নির্ধারণ করার জন্য। এগুলো ব্যবহার করে আপনি ওয়েব পেইজে বেশ ভাল ইন্টার-এক্টিভিটি দিতে পারবেন। এই চ্যাপ্টারে এসব স্টেটমেন্টের একটা ওভারভিউ দেওয়া হয়েছে।
সাধারণত স্ক্রিপ্ট অথবা কোন ফাংশনের ভেতর কোড এর গতিপথ থাকে ওপর থেকে নিচের দিকে, মানে ওপরের লাইনের পর নিচের লাইন কোড একজিকিউট করা হয়। কোডের গতিপথ পরিবর্তন করাই হল কন্ট্রোল ফ্লো'তে আলোচ্য বিষয়।
যেকোন এক্সপ্রেশন-ও স্টেটমেন্ট হিসেবে গণ্য হবে। এক্সপ্রেশন নিয়ে আরও তথ্যের জন্য Expressions এবং Operators দেখুন।
জাভাস্ক্রিপ্ট কোডে প্রতিটি স্টেটমেন্ট লেখার পর সেমিকোলন (;) দিন।
এই চ্যাপ্টারের স্টেটমেন্ট গুলো নিয়ে বিস্তারিত জানতে জাভাস্ক্রিপ্ট রেফারেন্স দেখুন।
ব্লক স্টেটমেন্ট
একাধিক স্টেটমেন্ট কে একই গ্রুপে ঢুকাতে ব্লক স্টেটমেন্ট ব্যবহার করা হয়। সব স্টেটমেন্ট যারা একজোড়া দ্বিতীয় বন্ধনীর "{}" ভেতর থাকে সেসব স্টেটমেন্ট একই ব্লকে থাকে।
{
statement_1;
statement_2;
.
.
.
statement_n;
}
উদাহরণ
ব্লক স্টেটমেন্ট প্রায়ই কন্ট্রল-ফ্লো স্টেটমেন্ট (যেমন if, for, while) এর সাথে ব্যবহার করা হয়।
while (x < 10){
x++;
}
এখানে, { x++; } হল ব্লক স্টেটমেন্ট।
গুরুত্বপূর্ণঃ জাভাস্ক্রিপ্টে ব্লকের ভেতর নতুন স্কোপ তৈরি হয় না। ব্লকের ভেতর নতুন ভেরিয়েবল তৈরি করলে তারা ব্লকের বাইরেও পুরো ফাংশনে, অথবা পুরো স্ক্রিপ্টেই ব্যবহারযোগ্য থাকে। যার মানে হল জাভাস্ক্রিপ্টে ব্লক তৈরি করলে ব্লকের ভেতর নতুন স্কোপ তৈরি হয় না। যদিও "standalone" ব্লক তৈরি করলে কোন ভুল হবে না, জাভাস্ক্রিপ্টে standalone (মানে পুরাপুরি স্বাধীন, অন্য কোন কোড যেমন ব্লল্কের বাইরের কোডের ওপর নির্ভর করে না) ব্লক তৈরি না করাই ভাল। কারণ আপনি যদি সি বা জাভা প্রোগ্রামিং করে থাকেন, তাহলে আপনি যেভাবে ভাবছেন আপনার কোড ঐভাবে আচরণ নাও করতে পারে। যেমনঃ
var x = 1;
{
var x = 2;
}
alert(x); // outputs 2
আউটপুট হিসেবে 2 পেয়েছি কারণ ব্লকের ভেতরের var x স্টেটমেন্ট x ভেরিয়েবলের নতুন কোন স্কোপ তৈরি করে নি। সি বা জাভাতে আউটপুট পাওয়া যেত 1।
কন্ডিশনাল স্টেটমেন্ট
কন্ডিশনাল (conditional) স্টেটমেন্ট হল এক/একাধিক স্টেটমেন্ট যেগুলো কোন একটা শর্ত সত্যি হলেই কাজ করবে। জাভাস্ক্রিপ্টে দু'টি কন্ডিশনাল স্টেটমেন্ট আছেঃ if...else আর switch।
if...else স্টেটমেন্ট
যখন আপনি চান কোন একটি লজিকাল শর্ত সত্যি হলেই কোন স্টেটমেন্ট কাজ করবে, তখন if স্টেটমেন্ট ব্যবহার করুন। আর যদি শর্তটি মিথ্যা হয় তাহলে কোন স্টেটমেন্ট কাজ করবে - সেসব স্টেটমেন্ট else ক্লজ দিয়ে লিখুনঃ
if (condition) statement_1 [else statement_2] // এগুলো কোড নয়, শুধু উদাহরণের জন্য দেওয়া হয়েছে। যা কিছু [] এর মধ্যে আছে সেগুলো // ঐচ্ছিক - মানে আপনার কোডের ওপর নির্ভর করে থাকতে পারে নাও থাকতে পারে।
ওপরে দেখানো condition যেকোন স্টেটমেন্ট হতে পারে - যা সত্যি বা মিথ্যা হিসেবে নির্ণয়যোগ্য হতে হবে। সত্যি/মিথ্যা (true এবং false) হিসেবে কারা কারা নির্ণয়যোগ্য তা জানার জন্য বুলিয়ান দেখুন। যদি condition সত্য হয়, তাহলে statement_1 কাজ করবে, আর মিথ্যা হলে statement_2 কাজ করবে। statement_1 আর statement_2 যেকোন স্টেটমেন্ট হতে পারে, এবং এগুলোর ভেতরেও আরও if স্টেটমেন্ট থাকতে পারে।
আপনি else if ব্যবহার করে একের অধিক কন্ডিশন বা শর্ত একের পর এক নির্ণয় করতে পারেন, যেমনঃ
if (condition) statement_1 [else if (condition_2) statement_2] ... [else if (condition_n_1) statement_n_1] [else statement_n] // এগুলো কোড নয়, শুধু উদাহরণের জন্য দেওয়া হয়েছে। যা কিছু [] এর মধ্যে আছে সেগুলো // ঐচ্ছিক - মানে আপনার কোডের ওপর নির্ভর করে থাকতে পারে নাও থাকতে পারে।
একের অধিক স্টেটমেন্ট চালাতে এদেরকে নিয়ে একটি ব্লক ({ ... }) তৈরি করুন। সাধারণতঃ সবসময়-ই ব্লক ব্যবহার করা ভাল, বিশেষ করে যখন একটি অনেক if স্টেটমেন্ট একটা আরেকটার মধ্যে থাকে।
if (condition) {
statement_1_runs_if_condition_is_true
statement_2_runs_if_condition_is_true
} else {
statement_3_runs_if_condition_is_false
statement_4_runs_if_condition_is_false
}
// এগুলো কোড নয়, শুধু উদাহরণের জন্য দেওয়া হয়েছে।
if (x = y) {
/* do the right thing */
}
আর আপনার যদি এসাইনমেন্ট করতেই হয়, তাহলে তাদের আগে অতিরিক্ত বন্ধনী দিয়ে নিনঃ
if ((x = y)) {
/* do the right thing */
}
নিচের মান গুলো মিথ্যা হিসেবে নির্ণিত হবেঃ
falseundefinednull0NaN- ফাঁকা স্ট্রিং (
"")
এছাড়া বাকি সকল মান (যেকোন অবজেক্ট সহ) সত্য হিসেবে নির্ণীত হবে যখন তাদের কন্ডিশনাল স্টেটমেন্টে ব্যবহার করা হয়।
প্রিমিটিভ (যা অবজেক্ট না) বুলিয়ান মান true এবং false কে Boolean অবজেক্টের true এবং false মানের সাথে এক করে ফেলা যাবে নাঃ
var b = new Boolean(false); if (b) // this condition evaluates to true
উদাহরণ
নিচের উদাহরণে checkData ফাংশন সত্য রিটার্ন করে যদি Text অবজেক্টের অক্ষরগুলোর সংখ্যা তিন হয়, অথবা এটি একটি এলার্ট দেখাবে আর মিথ্যা রিটার্ন করবে।
function checkData() {
if (document.form1.threeChar.value.length == 3) {
return true;
} else {
alert("Enter exactly three characters. " +
document.form1.threeChar.value + " is not valid.");
return false;
}
}
switch স্টেট্মেন্ট
switch স্টেটমেন্ট ব্যবহার করে আপনার প্রোগ্রাম কোন একটি এক্সপ্রেশন পরীক্ষা করে, এক্সপ্রেশনটি যেই মান দিবে সেই মান প্রোগ্রামার এর দেওয়া কোন অনেকগুলো মানের (যাদের case লেবেল বলা হয়) সাথে মেলানোর চেষ্টা করবে। যদি কোন লেবেলের সাথে মিলে যায়, সেই লেবেলের নিচে লেখা কোড গুলো একজিকিউট করা হয়। যেমনঃ
switch (expression) {
case label_1:
statements_1
[break;]
case label_2:
statements_2
[break;]
...
default:
statements_def
[break;]
}
ওপরের কোডে প্রথমে expression এর মান নির্ণয় করা হয় এবং দেখা হয়, এই মান কোন case লেবেল এর সাথে মিলেছে কিনা। মিলে গেলে, সেই লেবেলের নিচে লেখা স্টেটমেন্ট গুলো একজিকিউট করা হয়। যদি কোন লেবেলের সাথে না মিলে, তাহলে default লেবেলের নিচের স্টেটমেন্ট একজিকিউট করা হয়। এই default লেবেল চাইলে নাও দিতে পারেন, সেক্ষেত্রে switch ব্লকের পরের কোড যথানিয়মে একজিকিউট করা হবে। প্রথা হচ্ছে, default ক্লজ অন্য সব লেবেলের শেষে লেখা।
break স্টেটমেন্ট টি ঐচ্ছিক। যদি কোন case লেবেলের শেষে break লিখেন, তাহলে এই break পর্যন্ত কোড একজিকিউট পর কোডের গতিপথ switch ব্লক থেকে বের হয়ে চলে যাবে, আর সুইচ ব্লকের পরের কোড যথানিয়মে একজিকিউট করা হবে। কিন্তু যদি break না দেওয়া হয়, তাহলে সুইচ ব্লক থেকে বের হবে না, আর break এর পরের কোড গুলোও একজিকিউট করা হবে।
উদাহরণ
নিচের উদাহরণে যদি fruittype এর মান "Bananas" হিসেবে নির্ণিত হয়, তাহলে "Bananas" লেবেলের নিচে লেখা কোড একজিকিউট করা হবে। break পাওয়ার পর, switch ব্লক থেকে বের হয়ে কোডের নিয়ন্ত্রণ চলে যাবে switch ব্লকের পরের লাইনে। আর যদি break না দিতাম, তাহলে "Cherries" কেইসের কোড গুলোও একজিকিউট করা হত।
switch (fruittype) {
case "Oranges":
document.write("Oranges are $0.59 a pound.<br>");
break;
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Cherries":
document.write("Cherries are $3.00 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + fruittype + ".<br>");
}
document.write("Is there anything else you'd like?<br>");
লুপ স্টেটমেন্ট
যদি এক/একাধিক কমান্ড কে বারবার একজিকিউট করতে চান, (যতক্ষণ না কোন বিশেষ শর্ত পূরণ হচ্ছে) তাহলে লুপ স্টেটমেন্ট ব্যবহার করুন। জাভাস্ক্রিপ্টের লুপ স্টেটমেন্ট গুলো হচ্ছেঃ for, do while এবং while। এছাড়া label নামের লুপ স্টেটমেন্টও আছে, যদিও এটা নিজে কোন লুপিং এর কাজ করে না কিন্তু প্রায়ই ব্যবহৃত হয়। এছাড়া লুপ নিয়ন্ত্রণ করার জন্য break আর continue স্টেটমেন্ট ব্যবহার করা হয়।
আরও একধরণের স্টেটমেন্ট for...in-ও কোন স্টেটমেন্ট কে বারবার চালাতে পারে, তবে এরা মূলত ব্যবহার করা হয় অবজেক্ট নিয়ে কাজ করে অবজেক্টের ভেতর বিভিন্ন পরিবর্তন আনার জন্য। Object Manipulation Statements দেখুন।
লুপিং করার জন্য ব্যবহৃত স্টেটমেন্টগুলো হলঃ
- for স্টেটমেন্ট
- do...while Statement
- while Statement
- label Statement
- break Statement
- continue Statement
for স্টেটমেন্ট
আপনার দেওয়া কোন শর্ত মিথ্যা না হওয়া পর্যন্ত for লুপ চলতেই থাকবে, প্রতিবার ব্লকের শেষ লাইনে যাওয়ার পর আবার ব্লকের শুরু থেকে একজিকিউট করা হবে কোড। জাভা/সি এর মতইঃ
for ([initialExpression]; [condition]; [incrementExpression]) statement
for লুপ একজিকিউট হওয়ার সময় নিচের কাহিনীগুলো ঘটতে থাকেঃ
initialExpression, যদি দেওয়া হয় (এটি ঐচ্ছিক) তাহলে তা সবার আগে একজিকিউট করা হয়। এটা মূলতঃ লুপ এ আপনার লেখা কোন ভেরিয়েবল এর মান ইনিশিয়ালাইজ করার কাজে লাগে। এই অংশে ভেরিয়েবল তৈরিও করতে পারবেন।conditionএক্সপ্রেশন এর পর চালানো হয়। যদি এর মান সত্য হিসেবে নির্ণিত হয়, তাহলেstatementএকজিকিউট করা হয়। আর যদি এর মান মিথ্যা হয়, তাহলে লুপ থেকে বের হয়ে যাওয়া হয়, মানে লুপের পরের লাইনে কোডের নিয়ন্ত্রণ চলে যায়। যদিconditionএক্সপ্রেশন ও না দেওয়া হয়, তাহলে ধরে নেওয়া হয় এর মান সত্য।statementএকজিকিউট করা হয়। একাধিক চালাতে ব্লক স্টেটমেন্ট ({ ... }) ব্যবহার করুন, মানে দ্বিতীয় বন্ধনীর ভেতর স্টেটমেন্টগুলো লিখুন।incrementExpression, দেওয়া হলে তা একজিকিউট করা হয়, আর এরপর ওপরের ২ নাম্বার পয়েন্টে আবার কোডের গতিপথ চলে যায়।
উদাহরণ
নিচের ফাংশনে একটা for স্টেটমেন্ট দেখানো হয়েছে যার কাজ হল একটা স্ক্রলিং লিস্টের (Select অবজেক্ট যা একাধিক অপশন নির্বাচন করার সুবিধা দেয়) কোন কোন অপশন নির্বাচন করা হয়েছে তা গুণা। for স্টেটমেন্টটি i নামের ভেরিয়েবল তৈরি করে এর মান দিয়ে দিলো শূণ্য। এরপর বারবার যাচাই করা হয় এর মান options এর সংখ্যা থেকে কম আছে কিনা। কম থাকলে, এটি if ব্লক একজিকিউট করে। এরপর i এর মান এক বাড়িয়ে দেয় (৪থ স্টেপ)। লুপ চলতে থাকে যতক্ষণ না শর্ত মিথ্যা হয়।
<script>
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected)
numberSelected++;
}
return numberSelected;
}
</script>
<form name="selectForm">
<p>
<strong>Choose some music types, then click the button below:</strong>
<br/>
<select name="musicTypes" multiple="multiple">
<option selected="selected">R&B</option>
<option>Jazz</option>
<option>Blues</option>
<option>New Age</option>
<option>Classical</option>
<option>Opera</option>
</select>
</p>
<p>
<input type="button" value="How many are selected?"
onclick="alert ('Number of options selected: ' + howMany(document.selectForm.musicTypes))"/>
</p>
</form>
do...while Statement
The do...while statement repeats until a specified condition evaluates to false. A do...while statement looks as follows:
do statement while (condition);
statement executes once before the condition is checked. To execute multiple statements, use a block statement ({ ... }) to group those statements. If condition is true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops and control passes to the statement following do...while.
Example
In the following example, the do loop iterates at least once and reiterates until i is no longer less than 5.
do {
i += 1;
document.write(i);
} while (i < 5);
while Statement
A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:
while (condition) statement
If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop.
The condition test occurs before statement in the loop are executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution stops and control is passed to the statement following while.
To execute multiple statements, use a block statement ({ ... }) to group those statements.
Example 1
The following while loop iterates as long as n is less than three:
n = 0;
x = 0;
while (n < 3) {
n++;
x += n;
}
With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:
- After the first pass:
n= 1 andx= 1 - After the second pass:
n= 2 andx= 3 - After the third pass:
n= 3 andx= 6
After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.
Example 2
Avoid infinite loops. Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate. The statements in the following while loop execute forever because the condition never becomes false:
while (true) {
alert("Hello, world");
}
label Statement
A label provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.
The syntax of the label statement looks like the following:
label : statement
The value of label may be any JavaScript identifier that is not a reserved word. The statement that you identify with a label may be any statement.
Example
In this example, the label markLoop identifies a while loop.
markLoop:
while (theMark == true) {
doSomething();
}
break Statement
Use the break statement to terminate a loop, switch, or in conjunction with a label statement.
- When you use
breakwithout a label, it terminates the innermost enclosingwhile,do-while,for, orswitchimmediately and transfers control to the following statement. - When you use
breakwith a label, it terminates the specified labeled statement.
The syntax of the break statement looks like this:
break;break label;
The first form of the syntax terminates the innermost enclosing loop or switch; the second form of the syntax terminates the specified enclosing label statement.
Example 1:
The following example iterates through the elements in an array until it finds the index of an element whose value is theValue:
for (i = 0; i < a.length; i++) {
if (a[i] == theValue)
break;
}
Example 2: Breaking to a Label
var x = 0;
var z = 0
labelCancelLoops: while (true) {
console.log("Outer loops: " + x);
x += 1;
z = 1;
while (true) {
console.log("Inner loops: " + z);
z += 1;
if (z === 10 && x === 10) {
break labelCancelLoops;
} else if (z === 10) {
break;
}
}
}
continue Statement
The continue statement can be used to restart a while, do-while, for, or label statement.
- When you use
continuewithout a label, it terminates the current iteration of the innermost enclosingwhile,do-whileorforstatement and continues execution of the loop with the next iteration. In contrast to thebreakstatement,continuedoes not terminate the execution of the loop entirely. In awhileloop, it jumps back to the condition. In aforloop, it jumps to theincrement-expression. - When you use
continuewith a label, it applies to the looping statement identified with that label.
The syntax of the continue statement looks like the following:
continue;continuelabel;
Example 1
The following example shows a while loop with a continue statement that executes when the value of i is three. Thus, n takes on the values one, three, seven, and twelve.
i = 0;
n = 0;
while (i < 5) {
i++;
if (i == 3)
continue;
n += i;
}
Example 2
A statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program terminates the current iteration of checkj and begins the next iteration. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is completed, and checkiandj reiterates until its condition returns false. When false is returned, the program continues at the statement following checkiandj.
If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement.
checkiandj :
while (i < 4) {
document.write(i + "<br/>");
i += 1;
checkj :
while (j > 4) {
document.write(j + "<br/>");
j -= 1;
if ((j % 2) == 0)
continue checkj;
document.write(j + " is odd.<br/>");
}
document.write("i = " + i + "<br/>");
document.write("j = " + j + "<br/>");
}
Object Manipulation Statements
JavaScript uses the for...in, for each...in, and with statements to manipulate objects.
for...in Statement
The for...in statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows:
for (variable in object) {
statements
}
Example
The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values.
function dump_props(obj, obj_name) {
var result = "";
for (var i in obj) {
result += obj_name + "." + i + " = " + obj[i] + "<br>";
}
result += "<hr>";
return result;
}
For an object car with properties make and model, result would be:
car.make = Ford car.model = Mustang
Arrays
Although it may be tempting to use this as a way to iterate over Array elements, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the Array object, such as adding custom properties or methods, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.
for each...in Statement
for each...in is a loop statement introduced in JavaScript 1.6. It is similar to for...in, but iterates over the values of object's properties, not their names.
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for each (var item in obj) {
sum += item;
}
print(sum); // prints "26", which is 5+13+8
Comments
Comments are author notations that explain what a script does. Comments are ignored by the interpreter. JavaScript supports Java and C++-style comments:
- Comments on a single line are preceded by a double-slash (//).
- Comments that span multiple lines are preceded by /* and followed by */:
Example
The following example shows two comments:
// This is a single-line comment. /* This is a multiple-line comment. It can be of any length, and you can put whatever you want here. */
Exception Handling Statements
You can throw exceptions using the throw statement and handle them using the try...catch statements.
You can also use the try...catch statement to handle Java exceptions (though there is a bug 391642 with this). See Handling Java Exceptions in JavaScript and JavaScript to Java Communication for information.
Exception Types
Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is fairly common to throw numbers or strings as errors it is frequently more effective to use one of the exception types specifically created for this purpose:
throw Statement
Use the throw statement to throw an exception. When you throw an exception, you specify the expression containing the value to be thrown:
throw expression;
You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:
throw "Error2"; //String type
throw 42; //Number type
throw true; //Boolean type
throw {toString: function() { return "I'm an object!"; } };
catch block. The following example creates an object myUserException of type UserException and uses it in a throw statement.// Create an object type UserException
function UserException (message){
this.message=message;
this.name="UserException";
}
// Make the exception convert to a pretty string when used as a string (e.g. by the error console)
UserException.prototype.toString = function (){
return this.name + ': "' + this.message + '"';
}
// Create an instance of the object type and throw it
throw new UserException("Value too high");
try...catch Statement
The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches it.
The try...catch statement consists of a try block, which contains one or more statements, and zero or more catch blocks, containing statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block. If no exception is thrown in the try block, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try...catch statement.
The following example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (1-12), an exception is thrown with the value "InvalidMonthNo" and the statements in the catch block set the monthName variable to unknown.
function getMonthName (mo) {
mo=mo-1; // Adjust month number for array index (1=Jan, 12=Dec)
var months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul",
"Aug","Sep","Oct","Nov","Dec");
if (months[mo] != null) {
return months[mo]
} else {
throw "InvalidMonthNo" //throw keyword is used here
}
}
try {// statements to try
monthName=getMonthName(myMonth) // function could throw exception
}
catch (e) {
monthName="unknown"
logMyErrors(e) // pass exception object to error handler
}
The catch Block
You can use a catch block to handle all exceptions that may be generated in the try block.
catch (catchID) {
statements
}
The catch block specifies an identifier (catchID in the preceding syntax) that holds the value specified by the throw statement; you can use this identifier to get information about the exception that was thrown. JavaScript creates this identifier when the catch block is entered; the identifier lasts only for the duration of the catch block; after the catch block finishes executing, the identifier is no longer available.
For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.
try {
throw "myException" // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e) // pass exception object to error handler
}
The finally Block
The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.
You can use the finally block to make your script fail gracefully when an exception occurs; for example, you may need to release a resource that your script has tied up. The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the finally block closes the file before the script fails.
openMyFile();
try {
writeMyFile(theData); //This may throw a error
}catch(e){
handleError(e); // If we got a error we handle it
}finally {
closeMyFile(); // always close the resource
}
If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any return statements in the try and catch blocks:
function f() {
try {
alert(0);
throw "bogus";
} catch(e) {
alert(1);
return true; // this return statement is suspended until finally block has completed
alert(2); // not reachable
} finally {
alert(3);
return false; // overwrites the previous "return"
alert(4); // not reachable
}
// "return false" is executed now
alert(5); // not reachable
}
f(); // alerts 0, 1, 3; returns false
Nesting try...catch Statements
You can nest one or more try...catch statements. If an inner try...catch statement does not have a catch block, the enclosing try...catch statement's catch block is checked for a match.
Utilizing Error objects
Depending on the type of error, you may be able to use the 'name' and 'message' properties to get a more refined message. 'name' provides the general class of Error (e.g., 'DOMException' or 'Error'), while 'message' generally provides a more succinct message than one would get by converting the error object to a string.
If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the Error constructor. For example:
function doSomethingErrorProne () {
if (ourCodeMakesAMistake()) {
throw (new Error('The message'));
}
else {
doSomethingToGetAJavascriptError();
}
}
....
try {
doSomethingErrorProne();
}
catch (e) {
alert(e.name);// alerts 'Error'
alert(e.message); // alerts 'The message' or a JavaScript error message)
}