Javascriptでtry-catch文のテスト
(何番煎じかわかりませんが、、)
test.js
function getMonthName (mo) {
mo=mo-1; // 月の数字を配列のインデックスに合わせる (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"
}
}
// テスト1
console.log("Test1")
myMonth=1
try {
monthName=getMonthName(myMonth)
console.log(monthName)
}
catch (e) {
monthName="unknown"
console.log(e)
}
// テスト2
console.log("Test2")
myMonth=100
try {
monthName=getMonthName(myMonth)
console.log(monthName)
}
catch (e) {
monthName="unknown"
console.log(e)
}
実行
$ node test.js
Test1
Jan
Test2
InvalidMonthNo
finally
try,catchの後にfinallyを加えると、どちらの場合でも処理の最後に必ず実行される。
try {
...
}
catch (e) {
...
}
finally {
console.log("final statement")
}
例えば以下の通り
function getMonthName (mo) {
mo=mo-1; // 月の数字を配列のインデックスに合わせる (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"
}
}
// テスト1
console.log("Test1")
myMonth=1
try {
monthName=getMonthName(myMonth)
console.log(monthName)
}
catch (e) {
monthName="unknown"
console.log(e)
}
finally {
console.log("final statement")
}
// テスト2
console.log("Test2")
myMonth=100
try {
monthName=getMonthName(myMonth)
console.log(monthName)
}
catch (e) {
monthName="unknown"
console.log(e)
}
finally {
console.log("final statement")
}
実行
$ node test.js
Test1
Jan
final statement
Test2
InvalidMonthNo
final statement