在运行时打印源代码的行号 [英] To print a line number of the source code in runtime

查看:86
本文介绍了在运行时打印源代码的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中运行程序时,谁能帮我打印源代码的行号.

例如,在php中,我们可以使用宏__LINE__来获取源代码的行号.

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.

推荐答案

请参阅此链接.它在java中有一个示例源,指出发生异常的行号

http://www.dreamincode.net/forums/topic/22661-exception -basics-try-catch-finally/ [
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/[^]


可以从异常中获取的StackTraceElement包含此信息,例如以下示例:

The the StackTraceElement that you can get out of the exception holds this information, like in this example:

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());
        }
        
    }
}




希望这会有所帮助,
弗雷德里克(Fredrik)




Hope this helps,
Fredrik


这篇关于在运行时打印源代码的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆