Reputation: 11
I know how to throw an exception from a constructer and handle it in the main method.
but the way I know requires two steps :
1- creat a static object (holder) using the constructer with parameters that take variables.
2-creat an object using the constructer with a parameter that takes an object.
like this:
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;
}
}
this way makes the code too long.
is there an alternative way to throw an exception from constructor to main?
Upvotes: 0
Views: 26