Java Exception StackTrace is determined when new

I wrote the following code that "new exceptions in advance and reuse them".

package exceptiontest;

public class ExceptionTest {
    
    //Generate an exception here.
    private static final RuntimeException _e = new RuntimeException("hello"); // line: 6

    public static void main(String[] args) {
        //It is here to actually throw.
        throw _e; // line: 10
    }
}

The result is ...

Exception in thread "main" java.lang.RuntimeException: hello
	at exceptiontest.ExceptionTest.<clinit>(ExceptionTest.java:6)

Why?

Java seems to determine the StackTrace when it creates an instance of Exception.

With python, StackTrace appears when raise ( throw) is done, so I wrote it with the same feeling.

For example, even if you rewrite the code as follows ...

package exceptiontest;

public class ExceptionTest {
    
    //Generate an exception here.
    private static final RuntimeException _e = new RuntimeException("hello"); // line: 6
    
    private static void f1() {
        f2();
    }
    
    private static void f2() {
        throw _e;
    }

    public static void main(String[] args) {
        // main() --> f1() --> f2() --> throw _e
        f1();
    }
}

You will get a StackTrace on line 6 that is always new to Exception.

Exception in thread "main" java.lang.RuntimeException: hello
	at exceptiontest.ExceptionTest.<clinit>(ExceptionTest.java:6)

<clinit> is a static initializer for a class. The variable _e is declared as a static element of the class, so the StackTrace will be determined when the ExceptionTest class is loaded.

Bonus (in Python)

It works as expected (?).

_e = Exception('hello')

def f1():
    raise _e

if __name__ == '__main__':
    f1()
Traceback (most recent call last):
  File "/Users/username/Documents/workspace/raisetest/main.py", line 7, in <module>
    f1()
  File "/Users/username/Documents/workspace/raisetest/main.py", line 4, in f1
    raise _e
Exception: hello

Recommended Posts

Java Exception StackTrace is determined when new
Unexpected exception when using Java DateTimeFormatter
[Java] What is Concurrent Modification Exception?
What is java
[Java] Exception instance
What is Java <>?
java1.8 new features
What is Java
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
Java 12 new feature summary
Java 13 new feature summary
[java] throw an exception
Exception when closing try-with-resources
What is Java Encapsulation?
[Unresolved] An exception occurs when an SSH connection is executed using JSch from a Java 6 application.
What is Java technology?
What is Java API-java
What's new in Java 8
[Java] What is flatMap?
Java 10 new feature summary
[Java] What is JavaBeans?
[Java] What is ArrayList?
Java 14 new feature summary
What's new in Java 9,10,11
When using ExpandableListView with fragment, exception occurs when inheritance is ListFragment