使用“try and catch”创建新对象

时间:2016-05-05 17:35:35

标签: java exception

所以基本上我有一个带有构造函数的类,特别是说,是状态的构造函数。我只能在构造函数中创建一个新的State,我有一个城市类型区域( State有2个构造函数,都接受name和Region)。

代码如下所示:

public State(String Name, int Population, Region Capital) throws IllegalArgumentException {
    super(Name, Population);
    if(!(Capital.getRegionType() == RegionType.CITY)){
        System.out.println("ERROR");
        throw new java.lang.IllegalArgumentException();
    }
    this.Capital = Capital;
}

使用Enum类定义区域的类型。问题是我在测试类(主类)中创建一个新函数

     Region3 = new Region("BedRock", 23423,RegionType.VILLAGE); //
     try{
        State s2 = new State("Khemed", Region3); // This should not be possible because Region3 is a VILLAGE instead of a CITY 
     }catch(IllegalArgumentException e){
     }
     s2.addRegion(Region2);//Doesn´t work - Error
     s2.addRegion(Region1);//Doesn´t work - Error

这基本上是我的问题,最后两行给了我一个错误,说我没有初始化变量s2。

我试着在没有“try and catch”的情况下运行代码,看看我在构造函数中的if语句是否有效但是没有。

方法“add”是在超类状态(Contry)中定义的方法,它只允许向其添加状态。

希望你能提供帮助,因为我无法理解如何解决这个问题。

已添加(请回答我的问题)

班级地区:

public class Region {
private String name;
private int population;
private RegionType regionType;

public Region(String name, int population, RegionType regionType){
    this.name = name;
    this.population = population;
    this.regionType = regionType;
}

//get Region Type
public RegionType getRegionType(){
    return regionType;
}

区域类型的枚举:

public enum RegionType {
CITY,
VILLAGE,
TOWN,

}

3 个答案:

答案 0 :(得分:2)

您的变量s2仅在try/catch块中定义,请尝试将2行放在try/catch块中。

但这里最好的方法是避免捕获异常IllegalArgumentException

答案 1 :(得分:1)

Region3 = new Region("BedRock", 23423,RegionType.VILLAGE); //
 try{
    State s2 = new State("Khemed", Region3); 
    s2.addRegion(Region2);
    s2.addRegion(Region1);
 }catch(IllegalArgumentException e){
 }

首先,您必须将2行放入try / catch块。而你的“状态”构造函数有3个参数。但是你正在使用另一个构造函数(2个参数):

 State s2 = new State("Khemed", Region3); // 2 params 
public State(String Name, int Population, Region Capital)// 3 params

在try block中使用这样的population param:

Region3 = new Region("BedRock", 23423,RegionType.VILLAGE); //
 try{
    State s2 = new State("Khemed", 123,Region3); 
    s2.addRegion(Region2);
    s2.addRegion(Region1);
 }catch(IllegalArgumentException e){
 }

答案 2 :(得分:-1)

在第二个代码块中,s2仅在try块中具有范围。相反,请在s2之外声明try

编辑:这就是我发布太快的内容。 s2语句应位于try

 Region3 = new Region("BedRock", 23423,RegionType.VILLAGE);
 State s2 = null;
 try{
    s2 = new State("Khemed", Region3);
    s2.addRegion(Region2);
    s2.addRegion(Region1);
 }catch(EmptyStackException e){ //You should log this or something
 }