得到java異常printStackTrace的詳細資料

來源:互聯網
上載者:User

   平時寫java代碼時,想看拋出的異常資訊,來找出具體的異常點,我們常常會用Exception.toString ()或者 Exception.getMessage()來取得異常資訊,再把它print到控制台,,但是這些資訊只能告訴我們異常本身的資訊,對我們找出異常點協助並不太理想,所以我們會使用Exception.printStackTrace()方法,這樣就可以在控制台輸出非常詳細的異常資訊,甚至可以通過它跟蹤到異常發生在某個類的第幾行,這對我們非常有用。但是我們有時只想得到這些 StackTrace資料,通過其它方式表現出來(非控制台,如網頁或GUI),這就有了這篇文章.回想一下,原來的日誌工具log4、weblogic伺服器、還有webshpere伺服器等等好像都可以得到這些資訊,所以就先直接在Exception類找找有沒有直接的方法可以返回這些資訊,看到getStackTrace()方法返回一個StackTraceElement對象的集合(原來怎麼沒注意到呢?),翻一下JDK,一看StackTraceElement類提供的方法(

 
 String getFileName()

          Returns the name of the source file containing the execution point represented by this stack trace element.
 int getLineNumber()

          Returns the line number of the source line containing the execution point represented by this stack trace element.
 String getMethodName()

          Returns the name of the method containing the execution point represented by this stack trace element.
 int hashCode()

          Returns a hash code value for this stack trace element.
 boolean isNativeMethod()

          Returns true if the method containing the execution point represented by this stack trace element is a native method.
 String toString()

)沒錯,就是他了,寫段代碼測試一下先:

public static void main(String[] args) {
  try{
   byte[] a=args[0].getBytes();
   
  }catch (Exception ex){
   
   ex.printStackTrace();
   StackTraceElement [] messages=ex.getStackTrace();
   int length=messages.length;
   for(int i=0;i<length;i++){
    System.out.println("ClassName:"+messages[i].getClassName());
    System.out.println("getFileName:"+messages[i].getFileName());
    System.out.println("getLineNumber:"+messages[i].getLineNumber());
    System.out.println("getMethodName:"+messages[i].getMethodName());
    System.out.println("toString:"+messages[i].toString());
    }
   }
 }

Ok,秘密找到了,原來就這麼回事。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.