Home > Java > javaTutorial > body text

When to use fillInStackTrace() method in Java?

WBOY
Release: 2023-08-19 15:01:09
forward
1361 people have browsed it

When to use fillInStackTrace() method in Java?

In Java, fillInStackTrace() is an important method in the Throwable class. Stack traces can help determine where exactly an exception was thrown. In some cases we may need to rethrow the exception and find out where it was rethrown, we can use the fillInStackTrace() method in this case.

Grammar

<strong>public Throwable fillInStackTrace()</strong>
Copy after login

Example

Chinese translation is:

Example

public class FillInStackTraceTest {
   public static void method1() throws Exception {
      throw new Exception("This is thrown from method1()");
   }
   public static void method2() throws Throwable {
      try {
         method1();
      } catch(Exception e) {
         System.err.println("Inside method2():");
            e.printStackTrace();
            throw e.fillInStackTrace(); // <strong>calling fillInStackTrace() method</strong>
      }
   }
   public static void main(String[] args) throws Throwable {
      try {
         method2();
      } catch (Exception e) {
         System.err.println("Caught Inside Main method()");
         e.printStackTrace();
      }
   }
}
Copy after login

Output

Inside method2():
java.lang.Exception: This is thrown from method1()
        at FillInStackTraceTest.method1(FillInStackTraceTest.java:3)
        at FillInStackTraceTest.method2(FillInStackTraceTest.java:7)
        at FillInStackTraceTest.main(FillInStackTraceTest.java:18)
Caught Inside Main method()
java.lang.Exception: This is thrown from method1()
        at FillInStackTraceTest.method2(FillInStackTraceTest.java:12)
        at FillInStackTraceTest.main(FillInStackTraceTest.java:18)
Copy after login

The above is the detailed content of When to use fillInStackTrace() method in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!