java中定位当前异常的位置(行数)

案例:

有时候我们需要把自己捕获的异常,保存下来 那么就要精确的定位到哪一行报错

public static StringBuffer getTraceInfo(Exception e) {
  StringBuffer sb = new StringBuffer();
  StackTraceElement[] stacks = e.getStackTrace();
  for (int i = 0; i < stacks.length; i++) {
   if (stacks[i].getClassName().contains(this.getApplicaionName)) {
    sb.append("class: ").append(stacks[i].getClassName())
      .append("; method: ").append(stacks[i].getMethodName())
      .append("; line: ").append(stacks[i].getLineNumber())
      .append(";  Exception: ");
    break;
   }
  }
  return sb;
 }

 public static String getExceptionMessage(Exception e) {
  String message = e.toString();
  if (message.lastIndexOf(":") != -1)
   message = message.substring(0, message.lastIndexOf(":"));
  return getTraceInfo(e).append(message).toString();
 }


 

你可能感兴趣的:(java,exception,String,Class)