public class Test { public int div(int a, int b) { try { return a/b; } catch (Exception e) { e.printStackTrace(); } return 0; } public static void main(String[] args) { Test test = new Test(); test.div(3, 0); } }
打印結(jié)果:
e.printStackTrace()打印出異常,但是它還將顯示出更深的調(diào)用信息。它是一層一層的向外調(diào)查,最后都會(huì)回到com.glxt…..main(主函數(shù))。
它適合調(diào)試時(shí)使用。
2、toString()演示public class Test { public int div(int a, int b) { try { return a/b; } catch (Exception e) { System.out.println(e.toString()); } return 0; } public static void main(String[] args) { Test test = new Test(); test.div(3, 0); } }
打印結(jié)果:
3、getMessage()演示
public class Test { public int div(int a, int b) { try { return a/b; } catch (Exception e) { System.out.println(e.getMessage()); } return 0; } public static void main(String[] args) { Test test = new Test(); test.div(3, 0); } }
打印結(jié)果:
附注: 如何獲取e.printStackTrace()的內(nèi)容
e.printStackTrace()通常是打印在控制臺的,但是,有時(shí)候程序上線了需要看這個(gè)堆棧的內(nèi)容就不容易了,一來生產(chǎn)環(huán)境打印的東西很多或者很少,二來有時(shí)候無法直接查看到,這個(gè)時(shí)候就需要把這些內(nèi)容記錄下來,比如記錄到數(shù)據(jù)庫中,下面的方法可以完整記錄。
public static void main(String[] args) { try { String aa = ""; System.out.println(aa.substring(3));
} catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw, true)); String str = sw.toString(); System.out.println("==========");
System.out.println(str); } }
打印的效果如下:java.lang.StringIndexOutOfBoundsException: String index out of range: -3 at java.lang.String.substring(Unknown Source) at java.lang.String.substring(Unknown Source) at Getc.main(Getc.java:16) ========== java.lang.StringIndexOutOfBoundsException: String index out of range: -3 at java.lang.String.substring(Unknown Source) at java.lang.String.substring(Unknown Source) at Getc.main(Getc.java:16)
新聞熱點(diǎn)
疑難解答
圖片精選