Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can any one help me in printing the line number of the source code while running the program in java.

eg., in php we can use macro __LINE__ to get the line number of the source code.
Posted
Comments
TorstenH. 29-Mar-12 5:53am    
??? what? Do you have an exception popping up or what?

You can use an IDE, that one will show line numbers if told to do so.
Loke.mysore 29-Mar-12 6:02am    
Yes to show a exception with the line number so it can be debug easily
TorstenH. 29-Mar-12 6:39am    
both answers are correct and therefor +5 but you are also taking on to a rocket science kind of thing! How about the good old e.printStackTrace() ?
Loke.mysore 29-Mar-12 6:45am    
of course solution 1 was correct, Solution 2 helped me more..
TorstenH. 29-Mar-12 9:56am    
you can accept both I think.

Refer this link. It has a example source in java for the line number where exception occurs

http://www.dreamincode.net/forums/topic/22661-exception-basics-try-catch-finally/[^]
 
Share this answer
 
The the StackTraceElement that you can get out of the exception holds this information, like in this example:

Java
package my.company;

public class Program {


    public void foo(boolean a) throws Exception{
        bar(a);
    }
    
    public void bar(boolean a) throws Exception {
        if (a)
            throw new Exception("I was told to throw!");
    }

    public static void main(String[] args) {
        try {
            Program p = new Program();
            p.foo(true);
        }
        catch(Exception e) {
            System.out.println("Error caught:");
            System.out.println("\t" + e.getMessage());
            System.out.println("\tThrown in file " + e.getStackTrace()[0].getFileName());
            System.out.println("\tThrown on line " + e.getStackTrace()[0].getLineNumber());
        }
        
    }
}



Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900