-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.

Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191
  • 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? – Emissary Feb 08 '14 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. – Sukima Feb 08 '14 at 14:45

2 Answers2

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.

Sukima
  • 9,965
  • 3
  • 46
  • 60
  • 2
    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 – Renaud is Not Bill Gates Feb 08 '14 at 14:45
  • 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. – Sukima Feb 08 '14 at 14:48
-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

vitkon
  • 1,058
  • 8
  • 13