2010年4月17日 星期六

JAVA印出錯誤行數的方式

JDK 1.3(含)之前

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

public class DebugTest {

public static void main(String[] args) {
try{
String a = "test";
System.out.println(a.length());
a = null;
System.out.println(a.length());
}catch(Exception e){
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw, true);
e.printStackTrace(out);
System.out.println(sw.toString());
System.out.println(e.toString());
}

}

}


JDK 1.4含)之後

public class DebugTest {


public static void main(String[] args) {
try{
String a = "test";
System.out.println(a.length());
a = null;
System.out.println(a.length());
}catch(Exception e){
StackTraceElement[] ste = e.getStackTrace();
for(int i=0;i System.out.println(e.toString());
System.out.println(ste[0]);
System.out.println(ste.length);
System.out.println(e.toString());
}

}
}
}

可以搭配System.out.println(this.getClass().getResource("DebugTest_jsp.class"));取得JSP的class檔產生的在哪個路徑
比如在CentOS的Tomcat5上測試會產生file:/var/cache/tomcat5/work/Catalina/localhost/jsp-examples/org/apache/jsp/DebugTest_jsp.class

沒有留言:

張貼留言