What is the use of printStackTrace() method in Java?

后端 未结 10 1841
不知归路
不知归路 2020-12-02 06:35

I am going through a socket program. In it, printStackTrace is called on the IOException object in the catch block.
What does printStackT

10条回答
  •  长情又很酷
    2020-12-02 07:19

    What is the use of e.printStackTrace() method in Java?

    Well, the purpose of using this method e.printStackTrace(); is to see what exactly wrong is.

    For example, we want to handle an exception. Let's have a look at the following Example.

    public class Main{
    
      public static void main(String[] args) {
    
        int a = 12;
        int b = 2;
    
        try {
           int result = a / (b - 2);
           System.out.println(result);
        }
    
        catch (Exception e)
        {
           System.out.println("Error: " + e.getMessage());
           e.printStackTrace();
        }
      }
    }
    

    I've used method e.printStackTrace(); in order to show exactly what is wrong.

    In the output, we can see the following result.

    Error: / by zero
    
    java.lang.ArithmeticException: / by zero
    
      at Main.main(Main.java:10)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
    

提交回复
热议问题