Java中printStackTrace()、toString()、getMessage()的區別

來源:互聯網
上載者:User

標籤:

一、三者之間的關係圖:

二、示範 1、printStackTrace()示範:

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

列印結果:

e.printStackTrace()列印出異常,但是它還將顯示出更深的調用資訊。它是一層一層的向外調查,最後都會回到com.glxt…..main(主函數)。

它適合調試時使用。

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

列印結果:

 

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

列印結果:

 

附註: 如何擷取e.printStackTrace()的內容

e.printStackTrace()通常是列印在控制台的,但是,有時候程式上線了需要看這個堆棧的內容就不容易了,一來生產環境列印的東西很多或者很少,二來有時候無法直接查看到,這個時候就需要把這些內容記錄下來,比如記錄到資料庫中,下面的方法可以完整記錄。

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)

Java中printStackTrace()、toString()、getMessage()的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.