0

Hi I am getting a "undefined" with my custom error message.Why? I only want error message.Can anyone help please.

function divide() {
  let num = 2;
  let den = 0;
  try{
    if (den == 0){
      throw new Error("division invalid");
    }
    return Number(num/den);
  } catch(e){
    console.log(e.message);
  }
}
console.log(divide());
Rune FS
  • 21,497
  • 7
  • 62
  • 96
Negi Anurag
  • 31
  • 1
  • 6
  • Doesn't console.log() also return undefined? And since you are console logging twice explains why there are two undefined returns – Kitanga Nday Apr 28 '17 at 16:47

4 Answers4

2

Functions that don't have an explicit return, return undefined implicitly. You are throwing an error and then not returning anything in the catch block. Since you aren't returning a value, it sends undefined.

function divide() {
  let num = 2;
  let den = 0;
  try {
    if (den == 0) {
      throw new Error("division invalid");
     }
     return Number(num/den);
  } catch(e){
    console.log(e.message);
    return 'Can\'t divide by 0!';
  }
}

console.log(divide());

Notice in this code snippet that I am returning a string in the catch. The line return Number(num/den); is never called because there was an error.

adam-beck
  • 5,659
  • 5
  • 20
  • 34
1

Instead of logging the error within the function, you can return it to the calling method.

function divide() {
  let num = 2;
  let den = 0;
  try {
    if (den == 0) {
      throw new Error("division invalid");
    }
    return Number(num / den);
  } catch (e) {
    return e.message;
  }
}
console.log(divide());
Krypton
  • 4,394
  • 2
  • 9
  • 13
0

Console.log() function returns undefined. So do what @Krypton suggests, though that will still lead to the undefined still showing up. But hey, at least it's one less undefined, no?

Kitanga Nday
  • 3,517
  • 2
  • 17
  • 29
0

your code is working absolutely correct . I have tested this on my console. Most probably the problem is with your console settings, currently the console must be set to show errors only. So , change the chrome console output to Verbose or All. I am attaching the snapshot of how to change the settings and the output of your code as per your expectation. Solution to your problem Click here

For completeness: In the current version of chrome, the setting is no longer at the bottom but can be found when clicking the "Filter" icon at the top of the console tab (second icon from the left)

You can click here for further reference.

I hope this solves your problem . Thanks :)

Community
  • 1
  • 1
Prateek Gupta
  • 1,129
  • 1
  • 11
  • 24
  • Thanks. I got the solution. The issue was that I was doing a console.log for the divide function which threw a undefined. – Negi Anurag Apr 29 '17 at 03:13