使用了如下方法获得异常所在的文件,行号和方法:
StackTraceElement stackTraceElement= ex.getStackTrace()[0];// 得到异常棧的首个元素
System.out.println(\"Line=\"+stackTraceElement.getLineNumber());// 打印出错行号
System.out.println(\"Method=\"+stackTraceElement.getMethodName());// 打印出错方法
public class ExceptionTest{
public static void main(String[] arg) {
try{
翻阅JDK,我们找到StackTraceElement这个类。这个类可以从Throwable取得,另外也可以从Thread类取得,通过这些我写如下的一个打印行号的测试程序: 查看源代码