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)
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 astatic
element of the class, so the StackTrace will be determined when theExceptionTest
class is loaded.
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