0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javascriptでtry-catch文のテスト

Last updated at Posted at 2020-05-09

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

参考

開発者による開発者のためのリソース。try...catch 文

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?