LoginSignup
36
40

More than 1 year has passed since last update.

javascriptの例外処理

Last updated at Posted at 2017-03-02

想定外の例外的な事象が現れた時の対処法。

errorオブジェクト

const error = new Error("エラーメッセージ");

try...catch文

tryで何かしらの処理を実行して、そこで例外を吐き出した時にcatchがその例外をキャッチする。

try {
  console.log("正常の動作" );
} catch(error) {
  console.log("エラー内容:" + error);
}

例外のスロー 

throwを呼び出すと実行中の関数は即座に停止される。

例)2つの値を足し合わせて100以上なら例外をスローする

const add = (a,b) => {
  const add = a + b;
  if (100 > add) {
    throw new Error("100以上なのでエラー");
  } else {
    cosole.log("100より下");
  }
};

try...catch...finally

エラーであろうとなかろうがfinally構文に書いた処理は必ず実行される

try {
  console.log("処理中・・・");
  throw new Error("エラーです");
  console.log("エラーが起こるとスローされてここまで処理が実行されない");
} catch(error) {
  console.log("エラーが起きた!!!!");
} finally {
  console.log("どのような結果であれ、必ず実行される。");
}
36
40
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
36
40