本文介绍了我们可以在出现异常的try块中获取LineNumber和ColumnNumber的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下面的代码,我可以打印出完整类,类名,方法名,发生错误。
I have the below code with which i am able to print the fullclassname,classname,methodname, at which error occured.
此外,我可以打印行数字,但打印的行号是变量LineNumber被初始化的行。
Also, I am able to print Line-Number but the Line-Number printed is the line at which the variable "LineNumber" is initialized.
如何在try块中打印确切的LineNumber和ColumnNumber,错误发生?
How can i print the exact LineNumber and ColumnNumber in try block at which error occured?
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;
}
}
这篇关于我们可以在出现异常的try块中获取LineNumber和ColumnNumber的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!