2017.4.7 e.toString() 与 e.getMessage()的区别
生活随笔
收集整理的這篇文章主要介紹了
2017.4.7 e.toString() 与 e.getMessage()的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我使用的時候,拋出了空指針異常,本來是想將異常信息顯示在errorInfo里,卻發現沒有拿到錯誤信息。
原因:我用的是getMessage()。
1 用e.getMessage() 時,返回的是null。 2 用e.toString()時,才返回錯誤信息:空指針異常。?
Exception e中e的getMessage()和toString()方法的區別:
http://blog.sina.com.cn/s/blog_9e2578150102vkyk.html
?
示例代碼1:
1 public class TestInfo { 2 3 private static String str =null; 4 public static void main(String[] args) { 5 System.out.println("test exception"); 6 try { 7 if(str.equals("name")){ 8 System.out.println("test exception"); 9 } 10 } catch (Exception e) { 11 System.out.println(e.toString()); 12 System.out.println(e.getMessage()); 13 } 14 } 15 }?
輸出結果:
java.lang.NullPointerException null?
示例代碼2:
1 public class TestInfo { 2 3 private static int m = 0; 4 public static void main(String[] args) { 5 System.out.println("test exception"); 6 try { 7 m = 899/0; 8 } catch (Exception e) { 9 System.out.println(e.toString()); 10 System.out.println(e.getMessage()); 11 } 12 } 13 }?
輸出結果:
1 java.lang.ArithmeticException: / by zero 2 / by zero?
總結:由此可以看出,e.toString()獲取的信息包括異常類型和異常詳細消息,而e.getMessage()只是獲取了異常的詳細消息字符串。
?
轉載于:https://www.cnblogs.com/lyh421/p/6678360.html
總結
以上是生活随笔為你收集整理的2017.4.7 e.toString() 与 e.getMessage()的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: The Geometry has no
- 下一篇: 软件工程结对开发作业02