-1

I want to return the line number in my code, for example I want when I write console.log('SomeCode'); in the line 33 to return 33.

How can I do that in JavaScript?

I googled about it and I found this code :

try{ throw new Error('Buck stops here') }catch(e){ console.log( e.line) } 

But I don't want to use any try catch in my code.

2
  • 1
    Finding it from the stack trace is the only way. Try-catch is a valid construct, why don't you want to use it? Commented Feb 8, 2014 at 14:39
  • @Emissary I think the intent was to avoid the try / catch in his example, which in that case the try / catch is redundant since you could just assign the Error object to a variable instead of throwing and catching. Commented Feb 8, 2014 at 14:45

2 Answers 2

4

Skip the try / catch and just use the Error object:

var x = new Error("I want the line number"); console.log(x.lineNumber); 

More information is available at the MDN Docs

Also note that proprties like lineNumebr are implemented in specific interpreters and is not universal across all browsers.

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

2 Comments

When I tried this I got Indefined in console, I think the lineNumber property is valide on Firefox and Opera and not Google Chrome, because I'm using Google Chrome
if it is not available in your environment you might have to do your own regex parsing of x.stack to find it. There might be some snippets out there that do this.
-1

you need to catch all unhandled exceptions in your code. By doing this you won't need to put "try-catch" construction in.

window.onerror = function myErrorHandler(errorMsg, url, lineNumber) { console.log("Error occured: " + errorMsg + " on line " + lineNumber);//or any message return false; } 

MDN Reference

4 Comments

This feels like a code smell. It could easily mask legit runtime errors you might expect to throw.
Agreed. You can throw an error in this block if you want. Depends what you are trying to achieve.
While this technique may be useful in some circunstances, This is awful advice for the question asked.
I re-read the question and now I see that I didn't get it right ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.