6

In C/C++ the filename is returned by FILE and line number is returned by LINE. Java does have a getFileName(), but does not seem to have a corresponding getLineNumber(). It would be nice to be able to do something like this:

catch (Exception e) {
    System.err.println(this.getFileName() + this.getLineNumber() + e.getMessage());
}

Is there a way to get the java file/line number?

jacknad
  • 13,483
  • 40
  • 124
  • 194

2 Answers2

10
public static void main(String[] args)
{
    StackTraceElement frame = new Exception().getStackTrace()[0];
    System.out.println(frame.getFileName());
    System.out.println(frame.getLineNumber());
}
gawi
  • 13,940
  • 7
  • 42
  • 78
  • 6
    IMHO, it is better to do Thread.currentThread().getStackTrace() rather than constructing an Exception. Both are valid and working solutions though :) – Alain O'Dea Sep 08 '10 at 15:48
  • 1
    @Alain O'Dea I agree. I was not aware of/forgot about Thread.currentThread().getStackTrace() – gawi Sep 08 '10 at 16:21
3

Use this:

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html

gpeche
  • 21,974
  • 5
  • 38
  • 51