Java 中的 printStackTrace() 方法有什么用?

发布于 2024-08-27 05:28:40 字数 243 浏览 7 评论 0 原文

我正在经历一个套接字程序。其中,在 catch 块中的 IOException 对象上调用 printStackTrace
printStackTrace() 实际上做了什么?

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

我不知道它的目的。它有什么用?

I am going through a socket program. In it, printStackTrace is called on the IOException object in the catch block.
What does printStackTrace() actually do?

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

I am unaware of its purpose. What is it used for?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

许你一世情深 2024-09-03 05:28:40

这是 Exception 实例上的方法="noreferrer">将实例的堆栈跟踪打印到System.err

这是一个非常简单但非常有用的异常诊断工具。它告诉您发生了什么以及发生在代码中的位置。

下面是一个如何在实践中使用它的示例:

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

请注意,在“严肃的生产代码”中,由于各种原因(例如 System.out 不太有用,并且不是线程安全的)。在这些情况下,您通常会使用一些日志框架,该框架可以使用 log.error("Error during frobnication", e); 等命令提供相同(或非常相似)的输出。

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

沙沙粒小 2024-09-03 05:28:40

我对此也很好奇,所以我只是整理了一些示例代码,您可以在其中看到它在做什么:

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

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

调用 println(e):

java.lang.NullPointerException

调用e.printStackTrace()

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

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)
浅笑轻吟梦一曲 2024-09-03 05:28:40

它有助于追踪异常。例如,您正在程序中编写一些方法,而其中一种方法会导致错误。然后 printstack 将帮助您识别哪个方法导致了错误。堆栈将像这样提供帮助:

首先将调用主方法并将其插入堆栈,然后将调用第二个方法并按 LIFO 顺序插入堆栈,如果任何方法内的某个地方发生任何错误,则该堆栈将帮助识别该错误方法。

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.

扬花落满肩 2024-09-03 05:28:40

printStackTrace() 帮助程序员了解实际问题发生的位置。 printStacktrace()java.lang包的Throwable类的方法。它在输出控制台中打印几行。
第一行由几个字符串组成。它包含 Throwable 子类的名称和名称。包裹信息。
从第二行开始,它描述了以 at 开头的错误位置/行号。

最后一行始终描述受错误/异常影响的目标。倒数第二行告诉我们堆栈中的下一行,在从最后一行描述的行号进行传输后,控制权将移至何处。错误/异常以堆栈的形式表示输出,这些输出通过 Throwable 类的 fillInStackTrace() 方法送入堆栈,该方法本身填充程序控制传输详细信息进入执行堆栈。以 at 开头的行只不过是执行堆栈的值。
通过这种方式,程序员可以了解代码中的实际问题所在。

printStackTrace() 方法一起使用 e.getmessage() 是一个好主意。

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().

指尖上的星空 2024-09-03 05:28:40

printStackTrace() 打印源代码中发生异常的位置,从而使编写程序的作者能够看到出了什么问题。但由于它显示了源代码中的问题,因此无论是否有任何编码经验的用户都可能无法理解出了什么问题,因此如果程序允许用户向作者发送错误消息,则用户可能无法提供有关问题所在的详细数据。

您应该考虑 Logger.getLogger() 方法,它提供了更好的异常处理(日志记录)工具,此外不带参数的 printStackTrace() 被认为是过时的,应该仅用于调试目的,不用于用户显示。

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.

谁的年少不轻狂 2024-09-03 05:28:40

printStackTraceThrowable 类的一个方法。该方法在控制台显示错误消息;我们在源代码中得到异常的地方。这些方法可以与 catch 块一起使用,它们描述:

  1. 异常的名称。
  2. 异常的描述。
  3. 源代码中异常的位置。

描述控制台异常的三个方法(其中 printStackTrace 是其中之一)是:

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

示例:

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 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());  
         }
    }
}
固执像三岁 2024-09-03 05:28:40

printStackTrace() 帮助程序员了解实际问题发生的位置。 printStackTrace() 方法是 java.lang 包中 Throwable 类的成员。

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.

原野 2024-09-03 05:28:40

printStackTrace() 帮助程序员了解实际问题发生的位置。它有助于追踪异常。
它是每个异常类继承的 Throwable 类的 printStackTrace() 方法。此方法打印 e 对象的相同消息以及发生异常的行号。

下面是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:这是 Java 中的新异常...
在类名.方法名(文件名:5)

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)

落花浅忆 2024-09-03 05:28:40

Java中的e.printStackTrace()方法有什么用?

那么,使用这个方法e.printStackTrace();的目的就是看看到底出了什么问题。

例如,我们想要处理异常。我们来看看下面的例子。

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

我使用了方法 e.printStackTrace(); 来准确显示出了什么问题。

在输出中,我们可以看到以下结果。

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)

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)
追风人 2024-09-03 05:28:40

要捕获所有异常,您可以使用:

    } catch (Exception e) {
        println "An error occurred: ${e.message}"
        e.printStackTrace()
    }

对于任何其他情况:

    } catch ([ExceptionType] e) {
        println "An error occurred: ${e.message}"
        e.printStackTrace()
    }

for catching all exceptions you can use:

    } catch (Exception e) {
        println "An error occurred: ${e.message}"
        e.printStackTrace()
    }

for any other case:

    } catch ([ExceptionType] e) {
        println "An error occurred: ${e.message}"
        e.printStackTrace()
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文