Ich habe den folgenden Code geschrieben, der "neue Ausnahmen im Voraus und wiederverwendet".
package exceptiontest;
public class ExceptionTest {
//Generieren Sie hier eine Ausnahme.
private static final RuntimeException _e = new RuntimeException("hello"); // line: 6
public static void main(String[] args) {
//Es ist hier, um tatsächlich zu werfen.
throw _e; // line: 10
}
}
Das Ergebnis ist ...
Exception in thread "main" java.lang.RuntimeException: hello
at exceptiontest.ExceptionTest.<clinit>(ExceptionTest.java:6)
Java scheint StackTrace zu bestimmen, wenn es eine Instanz von Exception erstellt.
Für Python erscheint StackTrace, wenn
Raise(throw) fertig ist, also habe ich es mit dem gleichen Gefühl geschrieben.
Zum Beispiel, selbst wenn Sie den Code wie folgt umschreiben ...
package exceptiontest;
public class ExceptionTest {
//Generieren Sie hier eine Ausnahme.
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();
}
}
In Zeile 6 wird ein StackTrace angezeigt, der für Exception immer neu ist.
Exception in thread "main" java.lang.RuntimeException: hello
at exceptiontest.ExceptionTest.<clinit>(ExceptionTest.java:6)
<clinit>ist ein statischer Initialisierer für eine Klasse. Da die Variable_ealsstatischesElement der Klasse deklariert ist, wird die StackTrace bestimmt, wenn dieExceptionTestKlasse geladen wird.
Es funktioniert wie erwartet (?).
_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