LoginSignup
0
1

JavaScript try...catch

Last updated at Posted at 2023-11-21

try...catch文とは

結論

一言説明 : エラー特化のif文みてーなもん

ちゃんと説明

例えば、関数やクラスやオブジェクト、JSプログラムにおいて、
特定の条件が発生した場合に、意図的に(わざと)エラーを発生させたい場合に使うもの

実例

//関数定義
function checkDivisibleByFive(num) {
  let target = num % 5;
  var result;
  if(target == 0 ){
    result = true;
  }
  else{
    result = false;
  }
  return result
}


// try...catch 構文
try{
  const result = checkDivisibleByFive(4);
  if(result === false){
    throw new Error('5で割り切れない数字です');
  }
  else{
    console.log(result)
  }

}catch(e){
  console.error( e.message );
}

これを日本語で解説すると、

もし、5で割り切れる値を受け取ったら、true
5で割り切れない値を受け取ったら、5で割り切れない数字です
と、表示する
0
1
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
1