This post will discuss how to get the current line number in Java.

1. Using Throwable Stack Trace – Throwable.getStackTrace() method

We know that the Throwable class is the superclass of all errors and exceptions in Java. We can get an array of stack trace elements representing the stack trace pertaining to a throwable by calling getStackTrace() on a Throwable instance. The first element of the array represents the top of the stack, which is the last method invocation in the sequence.

Download  Run Code

Output:

The Current Line Number is 6

 
It is recommended to use the above code snippet inline. If we use it inside a method, this will return the line number of the method.

Download  Run Code

Output:

The Current Line Number is 5

 
We can also use the Exception class in place of the Throwable class as the Exception class extends the Throwable class.

2. Using Thread Stack Trace – Thread.getStackTrace() method

We can also use the stack trace of a current thread, which returns an array of stack trace elements representing the stack dump of this thread. The third element of the returned array of stack trace contains the stack frame of the calling method, which has the current line number info. To get the stack frame of the current method, use the second element of the returned array of the stack trace.

Download  Run Code

Output:

The Current Line Number is 9

 
The problem with using Throwable stack trace and Thread stack trace is that some virtual machines may skip one or more stack frames from the stack trace under some special circumstances.

That’s all about getting the current line number in Java.