示例:
@Test
public void testException(){
try {
double theorynumDouble = Double.parseDouble(null);
} catch (Exception e) {
StackTraceElement[] stackTraceElements =e.getStackTrace();
StackTraceElement stackTraceElementFirst = stackTraceElements[0];
String className = stackTraceElementFirst.getFileName();
String methodName = stackTraceElementFirst.getMethodName();
String lineNum = stackTraceElementFirst.getLineNumber()+"";
for(StackTraceElement ste : stackTraceElements){
if((this.getClass().getName()+".java").equals(ste.getFileName())){
methodName += "/"+ste.getMethodName();
lineNum += "/"+ste.getLineNumber();
className += "/"+ste.getFileName();
break;
}
}
String errorMsg = "异常信息:"+e.getMessage()+"。异常类:"+className+"。异常方法:"+methodName+"。异常行号:"+lineNum;
System.out.println(errorMsg);
}
}
效果: