Ich habe ein einfaches Programm mit dem Auslösen von Ausnahmen, und ich verstehe, dass Ausgabe bekomme ich, aber keine Ausnahme bekomme ich. Hier ist der Code:Einfache Java-Programm bricht beim Auslösen der Ausnahme
//Q1.java
import java.io.*;
import java.util.*;
public class Q1{
public static void main(String args[]){
Q1 q1=new Q1();
Q2 q2=new Q2();
try{
System.out.println(q2.method(q1));
System.out.println(q2.method(q2));
}catch(QE1 e){
System.out.println("exception 1");
}finally{
System.out.println("finally");
}
}
Object method(Q1 q) throws QE1{
if(q instanceof Q1){
System.out.println("method");
}
else {
throw new QE2();
}
return 1;
}
}
class Q2 extends Q1{
Object method(Q1 q) throws QE1{
if(errorCheck()&& q instanceof Q2){
throw new QE2("error 2");
}else if(q instanceof Q2){
throw new QE1();
}else{
return new String("abc");
}
}
boolean errorCheck(){
return true;
}
}
class QE1 extends Throwable{
public QE1(){
System.out.println("qe1 - 1");
}
public QE1(String s){
super(s);
System.out.println("qe1 - 2");
}
}
class QE2 extends RuntimeException {
public QE2(){
System.out.println("qe2 - 1");
}
public QE2(String s){
this();
System.out.println("qe2 - 2");
}
}
Ausgang ist:
abc
qe2 - 1
qe2 - 2
finally
QE2
at Q2.method(Q1.java:33)
at Q1.main(Q1.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:497)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
und dann Programmunterbrechungen, aber ich bin nicht sicher, warum.
Problematische Linie ist die im Konstruktor von QE2.
Ich nehme an, dass, weil QE2 eine Unterklasse von RuntimeException ist und deshalb der Konstruktor von RuntimeException aufgerufen wird, also bricht das Programm ab.
Ist das der Fall oder etwas anderes?
Was meinst du mit "Pausen". Bitte fügen Sie die Stapelverfolgung hinzu, die Sie erhalten! Sie sehen, dieser Code ist wahrscheinlich absichtlich so geschrieben, dass er schwer zu lesen ist. Glaubst du wirklich, dass dies ein guter Input für andere Leute ist? Sie machen es 10 Mal schwerer für uns, Ihnen zu helfen; nur wegen dieser zu komplizierten Code drin. – GhostCat
erhalten Sie einen Stacktrace in der Befehlszeile? Wenn ja, bitte zeigen. –
Es kann auch hilfreich sein, Ihren Klassen- und Methodennamen etwas Bedeutungsvolles zu geben. Nennen Sie es "Q1" und "Q2" und "Methode" wird Sie sehr schnell verwirrt. Sie können tun, was Sie wollen, aber das ist schlechte Übung imo. – Matt1776