jacknad
jacknad

Reputation: 13739

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

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?

Upvotes: 6

Views: 5479

Answers (2)

gawi
gawi

Reputation: 14227

public static void main(String[] args)
{
    StackTraceElement frame = new Exception().getStackTrace()[0];
    System.out.println(frame.getFileName());
    System.out.println(frame.getLineNumber());
}

Upvotes: 10

Related Questions