Java異常中getMessage()與toString的區別

Exception e中e的getMessage()和toString()方法的區別java

示例代碼1spa

public class TestInfo {
    private static String str =null;
    public static void main(String[] args) {
        System.out.println("test exception");
        try {
            if(str.equals("name")){
                System.out.println("test exception");
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            System.out.println(e.getMessage());
        }
    }
}

輸出結果:
java.lang.NullPointerException
null
示例代碼2:.net

public class TestInfo {
    private static int m = 0;
    public static void main(String[] args) {
        System.out.println("test exception");
        try {
            m = 899/0;
        } catch (Exception e) {
            System.out.println(e.toString());
            System.out.println(e.getMessage());
        }
    }
}

輸出結果:code

java.lang.ArithmeticException: / by zero
/ by zero
總結:blog

e.toString(): 得到異常種類和錯誤信息get

e.getMessage():得到錯誤信息it

e.printStackTrace():在控制檯打印出異常種類,錯誤信息和出錯位置等
---------------------
原文連接:https://blog.csdn.net/opera95/article/details/74885827io

相關文章
相關標籤/搜索