Errorオブジェクト
name
message
の2つのプロパティがある
err.js
const err = Error("エラーオブジェクト");
console.log(err.name);
// >> Error
console.log(err.message);
// >> エラーオブジェクト
try/catch構文
例外が発生し得る場合にtry/catch構文を使用します。
try-catch.js
try{
console.log("定義していないundefinedFuncを使用します")
undefinedFunc()
} catch(err) {
console.log("エラーが発生しました")
console.log(error.name)
// >> ReferenceError
console.log(error.message)
// >> undefinedFunc is not defined
} finally {
console.log("finallyの中は例外の有無に関わらず実行されます")
}
throw
例外を投げることができる。
throw.js
try {
throw new Error("例外を投げる");
} catch (err) {
console.log(err.name)
// >> Error
console.log(err.message)
// >> 例外を投げる
}