LoginSignup
3
3

More than 3 years have passed since last update.

JavaScriptエラーハンドリング

Posted at

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)
  // >> 例外を投げる
}
3
3
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
3
3