Home > front end >  how to write a function that handles error in javascript?
how to write a function that handles error in javascript?

Time:07-23

Your help and expertise is much appreciated.

How can do I write the error handling (try bloc) if the return value is not a number?

in this case, if the sum of 4 4 = 8 console.log(8) else, throw an error "error, input is not a number".

let total = sum(4, 4);

function sum (a, b){
    //check data type first and throw error
   
    return a   b;

}

console.log(total)

CodePudding user response:

You can verify if both the inputs are number using typeof and throw an error if not.

function sum(a, b) {
  if (typeof a !== "number" || typeof b !== "number") {
    throw new Error("Inputs must be a number");
  }
  return a   b;
}

let total = sum(4, 4);
console.log(total);

try {
  sum("4", 4);
} catch (err) {
  console.log(err.message);
}

CodePudding user response:

You can check data type by typeof and then throw Error with if statement. Also checking a number by typeof isn't enough because typeof NaN is also number. So We will do a extra step to be sure the parameter is number.

function isNumber(num) {
    if (typeof num === 'number') {
        return num - num === 0;
    }
    return false;
}

function sum (a, b){
    
    if(!isNumber(a) || !isNumber(b)) {
        throw new Error('error, input is not a number');
    }
    return a   b;

}

try {
   let total = sum(4, 4);
   console.log(total);
}
catch (err) {
   console.log(err.message);
}

try {
   let total = sum("4", 4);
   console.log(total);
}
catch (err) {
   console.log(err.message);
}

And you can also move try catch into your sum function if It works in your situation:

function isNumber(num) {
  if (typeof num === 'number') {
    return num - num === 0;
  }
  return false;
}

function sum (a, b){

  try {
    if(!isNumber(a) || !isNumber(b)) {
      throw new Error('error, input is not a number');
    }
  }
  catch(err) {
    return err.message;
  }

  return a   b;

}

let total = sum("4", 4);
console.log(total);
total = sum(4, 4);
console.log(total);

CodePudding user response:

you can use isNan() function or similar function who exist in Javascript for make your differents verifications, have a good day. Hope this will help you man.

  • Related