我有下面的代码,我可以用它打印出发生错误的完整类名,类名,方法名。
另外,我能够打印Line-Number,但是打印的Line-Number是初始化变量“LineNumber”的行。
如何在出现错误的try块中打印确切的LineNumber和ColumnNumber?
try
{
SQL Query
}
catch(Exception e)
{
String fullClassName = Thread.currentThread().getStackTrace()[1].getClassName();
String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
int lineNumber = Thread.currentThread().getStackTrace()[1].getLineNumber();
JOptionPane.showMessageDialog(null,fullClassName+"--"+className+"--"+methodName+"--"+lineNumber,"Error In Moving data from table1 to table2",JOptionPane.ERROR_MESSAGE);
}
Ouput:
IPM.Shifting--Shifting--ConfirmTransfer_BActionPerformed--1138
最佳答案
public class ExceptionHandler {
/**
* @param args
*/
public static void main(String[] args) {
try {
String str = getString();
if(str.isEmpty()){
System.out.println("error");
}
} catch (Exception e) {
StackTraceElement[] elements = e.getStackTrace();
for (int iterator=1; iterator<=elements.length; iterator++)
System.out.println("Class Name:"+elements[iterator-1].getClassName()+" Method Name:"+elements[iterator-1].getMethodName()+" Line Number:"+elements[iterator-1].getLineNumber());
}
}
private static String getString() {
jhgfjkhgjh();
return null;
}
private static void jhgfjkhgjh() {
gfdhdfghdg();
}
private static void gfdhdfghdg() {
sdfytusdgsfd();
}
private static void sdfytusdgsfd() {
throw null;
}
}
关于java - 我们可以在发生异常的try块中获取行号和列号吗,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14235687/