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()); 
1
  • Doesn't console.log() also return undefined? And since you are console logging twice explains why there are two undefined returns Commented Apr 28, 2017 at 16:47

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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());

Comments

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 :)

1 Comment

Thanks. I got the solution. The issue was that I was doing a console.log for the divide function which threw a undefined.
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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.