PrintStackTrace()方法在 Java 中的用途是什么?

我正在通过一个套接字程序。在该程序中,对 catch 块中的 IOException对象调用 printStackTrace
printStackTrace()实际上是做什么的?

catch(IOException ioe)
{
ioe.printStackTrace();
}

我不知道它的用途,它是干什么用的?

466800 次浏览

It's a method on Exception instances that prints the stack trace of the instance to System.err.

It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.

Here's an example of how it might be used in practice:

try {
// ...
} catch (SomeException e) {
e.printStackTrace();
}

Note that in "serious production code" you usually don't want to do this, for various reasons (such as System.out being less useful and not thread safe). In those cases you usually use some log framework that provides the same (or very similar) output using a command like log.error("Error during frobnication", e);.

It helps to trace the exception. For example you are writing some methods in your program and one of your methods causes bug. Then printstack will help you to identify which method causes the bug. Stack will help like this:

First your main method will be called and inserted to stack, then the second method will be called and inserted to the stack in LIFO order and if any error occurs somewhere inside any method then this stack will help to identify that method.

I was kind of curious about this too, so I just put together a little sample code where you can see what it is doing:

try {
throw new NullPointerException();
}
catch (NullPointerException e) {
System.out.println(e);
}


try {
throw new IOException();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);

Calling println(e):

java.lang.NullPointerException

Calling e.printStackTrace():

java.io.IOException
at package.Test.main(Test.java:74)

printStackTrace() prints the locations where the exception occurred in the source code, thus allowing the author who wrote the program to see what went wrong. But since it shows problems in the source code, the user(s) who may or may not have any coding experience may not be able to understand what went wrong, so if the program allows the user to send error messages to the authors, the users may not be able to give good data on what went wrong.

You should consider the Logger.getLogger() method, it offers a better exception handling (logging) facility, and besides printStackTrace() without arguments is considered to be obsolete and should ONLY be used for debugging purposes, not for user display.

printStackTrace() helps the programmer to understand where the actual problem occurred. printStacktrace() is a method of the class Throwable of java.lang package. It prints several lines in the output console. The first line consists of several strings. It contains the name of the Throwable sub-class & the package information. From second line onwards, it describes the error position/line number beginning with at.

The last line always describes the destination affected by the error/exception. The second last line informs us about the next line in the stack where the control goes after getting transfer from the line number described in the last line. The errors/exceptions represents the output in the form a stack, which were fed into the stack by fillInStackTrace() method of Throwable class, which itself fills in the program control transfer details into the execution stack. The lines starting with at, are nothing but the values of the execution stack. In this way the programmer can understand where in code the actual problem is.

Along with the printStackTrace() method, it's a good idea to use e.getmessage().

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)

The printStackTrace() helps the programmer understand where the actual problem occurred. The printStackTrace() method is a member of the class Throwable in the java.lang package.

printStackTrace is a method of the Throwable class. This method displays error message in the console; where we are getting the exception in the source code. These methods can be used with catch block and they describe:

  1. Name of the exception.
  2. Description of the exception.
  3. Location of the exception in the source code.

The three methods which describe the exception on the console (in which printStackTrace is one of them) are:

  1. printStackTrace()
  2. toString()
  3. getMessage()

Example:

public class BabluGope {
public static void main(String[] args) {
try {
System.out.println(10/0);
} catch (ArithmeticException e) {
e.printStackTrace();
// System.err.println(e.toString());
//System.err.println(e.getMessage());
}
}
}

printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.

The following is an another example of print stack of the Exception in Java.

public class Demo {
public static void main(String[] args) {
try {
ExceptionFunc();
} catch(Throwable e) {
e.printStackTrace();
}
}
public static void ExceptionFunc() throws Throwable {
Throwable t = new Throwable("This is new Exception in Java...");


StackTraceElement[] trace = new StackTraceElement[] {
new StackTraceElement("ClassName","methodName","fileName",5)
};
t.setStackTrace(trace);
throw t;
}
}

java.lang.Throwable: This is new Exception in Java... at ClassName.methodName(fileName:5)