我知道如何从构造方法中引发异常并通过main方法处理它。
但是我所知道的方式需要两个步骤:
1-使用构造函数创建带有包含变量的参数的静态对象(持有人)。
2-使用带有接受对象的参数的构造方法创建对象。
像这样:
import java.util.Scanner;
public class Test { // open Test class.
public static void main(String[] argus) { //open main method
Scanner input = new Scanner(System.in);
try {
CHILD.holder = new CHILD("A", -1);
} catch (Exception e) {
System.out.println("reEnter:");
int b = input.nextInt();
if (b < 0)
System.out.println("unvalid");
CHILD.holder.setB(b);
}
CHILD obj = new CHILD(CHILD.holder);
} //end main method
} // end Test class.
class SUPER {
private String A;
public SUPER() {}
public SUPER(String a) {
A = a;
}
public void setA(String a) {
A = a;
}
public String getA() {
return A;
}
}
class CHILD extends SUPER {
public static CHILD holder = new CHILD();
private int B;
public CHILD() {}
public CHILD(String a, int b) throws Exception {
holder.setA(a);
holder.B = 0;
if (b < 0)
throw new Exception("unalid , negative");
holder.B = b;
}
public CHILD(CHILD obj) {
super(obj.getA());
B = obj.B;
}
public void setB(int b) {
B = b;
}
}
这样会使代码太长。
是否有另一种方法可以从构造函数向main抛出异常?