1. 程式人生 > >列印異常資訊 方法彙總

列印異常資訊 方法彙總

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


          Returns the name of the source file containing the execution point represented by this stack trace element.
 int
          Returns the line number of the source line containing the execution point represented by this stack trace element.

          Returns the name of the method containing the execution point represented by this stack trace element.
 int
          Returns a hash code value for this stack trace element.
 boolean
          Returns true if the method containing the execution point represented by this stack trace element is a native method.
)沒錯,就是他了,寫段程式碼測試一下先:

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());
    }
   }
 }

2.

import java.io.PrintWriter;
import java.io.StringWriter;

public class PrintWriterTest {
public static void main(String[] args) {
   try{
    Exception ex = new Exception("aaa");
    throw ex;
   }catch (Exception e) {
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    System.out.println("*****="+sw.getBuffer().toString());
   }

}

}